Mam pytanie:
Czy da się ten kod zapisać jako list comprehension?
buy,sell = 0,0
for i, j in data:
if j == data[0][1]:
if i == ‘buy’:
buy += 1
else:
sell += 1
I think it’s also useful to understand list comprehensions. They are “do something to every item in the list, and return a new list”. They are very similar to a map(): Map (higher-order function) - Wikipedia
So if the length of your output list is not the length of your input list, you cannot use a list comprehension generally.
Having said that, the kind of thing you’re looking for is reduce(): Fold (higher-order function) - Wikipedia
import functools
data = [
["sell", "apple"],
["sell", "pear"],
["buy", "orange"],
["sell", "apple"],
["buy", "apple"],
["sell", "apple"],
["sell", "apple"],
]
(buy, sell) = functools.reduce(lambda prev, dataitem: prev if dataitem[1] != data[0][1] else ((prev[0] + 1, prev[1]) if dataitem[0] == "buy" else (prev[0], prev[1] + 1)), data, (0, 0))
print(buy, sell)
Reactions:
×1 (DoomHammer)
Both of these methods are a form of functional programming (Functional programming - Wikipedia), which is an extremely cool and powerful programming paradigm (and I would advise anyone who wants to become a good programming to do at least some functional programming exercises!
I think it’s a very good sign that you looked at your loop code and thought “this feels like something that could be improved”. So yes, it is ![]()
Having said that, in Python I would always write the original loop rather that the reduce function, just because the reduce function is hard to read for most people (even those that are experienced in reduces).
Reactions:
×1 (DoomHammer)
I think personally I would do something like:
data = [
["sell", "apple"],
["sell", "pear"],
["buy", "orange"],
["sell", "apple"],
["buy", "apple"],
["sell", "apple"],
["sell", "apple"],
]
assert(len(data) > 0)
interested_item_lines = [line for line in data if line[1] == data[0][1]]
sell = len([line for line in interested_item_lines if line[0] == "sell"])
buy = len(interested_item_lines) - sell
(exercise for the reader as to why there is an assert() there).
Or, @miwojc 's solution with Counter is very elegant as well!
Reactions:
×1 (DoomHammer)
Ah, but don’t underestimate learning to do functional programming. You can read some websites and do some simple exercises in an afternoon, but this is not “learning to program in a language”
Of course, I’m practicing functional programming! The reason I asked about it is every time I’ll check stackoverflow everyone uses list comprehension so I thought I need to use it whenever I can as well to look like pro ![]()
But thanks to you guys, now I know, readable code is the most important
Glad I asked about it, now I know more