Reputation: 2311
Is there a shorter way to write
for x in [x for x in X if a(x)]:
<Do something complicated with x>
Unfortunately, the following does not work:
for x in X if a(x):
<Do something complicated with x>
Of course, I could achieve the desired result by
for x in X:
if a(x):
<Do something complicated with x>
but this would introduce an extra level of indentation
Upvotes: 7
Views: 2856
Reputation: 1411
Not everyone is a fan of the following, but I quite like the map and filter funcs for readability...
list(map(b, filter(a, X))
It will achieve what you want, and I think it's easier to see what's going on.
Upvotes: 1
Reputation: 81594
[b(x) for x in X if a(x)]
is the simplest but will create an unnecessary list.
map(b, (x for x in X if a(x)))
will use a generator so no unneeded list will be created.
Upvotes: 5