2 ms·
I 'got' list comprehensions fairly immediately and find them clearer in most cases than map/filter for an explicit loop. I'm cautious when nesting them (as long
by andybak 11y ago
I 'got' list comprehensions fairly immediately and find them clearer in most cases than map/filter for an explicit loop. I'm cautious when nesting them (as long as your code formatting is clear - a single nested comprehension is pretty acceptable) and I never use the multiple 'for' form as it's just not intuitive to me.
I am rather fond of dictionary comprehensions as mentioned in the article:
colors = [jedi['lightsaber_color'] for jedi in jedis]
frequencies = {color: colors.count(color) for color in set(colors)}
print(frequencies)
# {'green': 6, 'red': 5, 'blue': 6}
- bpicolo 11y agoI think the biggest reason python map/filter aren't natural is the building outwards (though I do realize it's lispy and some people might prefer it). Languages that support it directly on a list are much more intuitive in my head: list.filter().map()... Alternatively, pull in syntax like elixir (and other languages) have to make chaining a breeze: list |> map() |> filter()