This question already has an answer here:
-
How to set local variable in list comprehension?
7 answers
Here a generic Python question about generators/list comprehension.
For a given iterable x
I need a list comprehension which looks like this:
[ flatten(e) for e in x if flatten(e) != '' ]
The function flatten
is potentially expensive, so it would be nice to call it only once. Is there a way to do this in an expressive one-liner?
Nest a generator:
[item for item in (flatten(e) for e in x) if item != '']
Or:
[item for item in map(flatten, x) if item != '']
Not really... Generally, I'd advise doing this in 2 steps. The first step flattens, the second step filters:
flattened = (flatten(e) for e in x)
[f for f in flattened if f]
You could put the generator into the list-comp, but I find that doing that tends to hurt readability for little gain (IMHO).
You could also write:
list(filter(None, map(flatten, e)))
But I don't think that's better :-)
Use map
function.
[ e for e in map(flatten, x) if e != '' ]