Do a function call in a list comprehension only on

2019-06-27 16:20发布

问题:

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?

回答1:

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 != '']


回答2:

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 :-)



回答3:

Use map function.

[ e for e in map(flatten, x) if e != '' ]