3 ms·
It's equivalent to planets_flat = [] for episode in episodes.values(): for planet in episode['planets']: plants_flat.append(planet) Notice how t
by thomasahle 11y ago
It's equivalent to
planets_flat = []
for episode in episodes.values():
for planet in episode['planets']:
plants_flat.append(planet)
Notice how the for loops in the comprehension goes in the same order as in the imperative code.
- hobarrera 11y ago> Notice how the for loops in the comprehension goes in the same order as in the imperative code. Thanks, that's a sane way to explain the order. Up to right now, it was always "the opposite of what you'd expect", which was a memory rule that always failed me.
- thomasahle 11y agoIt also works with the if-filtering, which usually goes in the inner most loop. Actually I don't recall if you can put an if between two for's, like you might do in an imperative loop.
- thomasahle 11y agoIt also helps on how ifs should be inserted, for example: ys = [] for x in xs: if P(x): for y in Y(x): if Q(x,y): ys.append(y) Becomes [y for x in xs if P(x) for y in Y(x) if Q(x,y) ] Surely combining this many for/if's may often be the wrong idea. Just like making a depth 4 iterative loop isn't always ideal. It does make the order easier to remember though :)
- craigds 11y agoWhich is why you should probably avoid nesting list comprehensions. A normal for loop with a single list comprehension inside it works just as well, and is far easier to read.