如果需要两次,只在列表推导中执行一次函数调用

时间:2016-12-13 00:47:02

标签: python generator list-comprehension

这是关于生成器/列表理解的一般Python问题。

对于给定的可迭代x,我需要一个列表推导,如下所示:

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

函数flatten可能很昂贵,所以最好只调用一次。有没有办法在富有表现力的单行中做到这一点?

3 个答案:

答案 0 :(得分:5)

嵌套发电机:

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

或者:

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

答案 1 :(得分:3)

不是......一般来说,我建议分两步完成。第一步是扁平化,第二步是过滤:

flattened = (flatten(e) for e in x)
[f for f in flattened if f]

您可以将生成器放入list-comp中,但我发现这样做往往会损害可读性而获得微不足道的收益(恕我直言)。

可以也写:

list(filter(None, map(flatten, e)))

但我不认为这样做更好: - )

答案 2 :(得分:0)

使用map功能。

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