如果需要两次,则仅在列表理解中执行一次函数调用 [英] Do a function call in a list comprehension only once if needed twice
本文介绍了如果需要两次,则仅在列表理解中执行一次函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是有关生成器/列表理解的通用Python问题.
Here a generic Python question about generators/list comprehension.
对于给定的可迭代x
,我需要一个如下所示的列表理解:
For a given iterable x
I need a list comprehension which looks like this:
[ flatten(e) for e in x if flatten(e) != '' ]
函数flatten
可能很昂贵,因此最好只调用一次.有一种表达方式可以做到这一点吗?
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?
推荐答案
嵌套一个生成器:
[item for item in (flatten(e) for e in x) if item != '']
或者:
[item for item in map(flatten, x) if item != '']
这篇关于如果需要两次,则仅在列表理解中执行一次函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文