如何有效地过滤Python列表推导中的计算值? [英] How do I efficiently filter computed values within a Python list comprehension?
问题描述
Python列表理解语法可轻松过滤理解中的值.例如:
The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:
result = [x**2 for x in mylist if type(x) is int]
将返回mylist中整数平方的列表.但是,如果测试涉及某些(昂贵的)计算并且您想要对结果进行过滤该怎么办?一种选择是:
Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is:
result = [expensive(x) for x in mylist if expensive(x)]
这将导致生成一个非"false"的昂贵(x)值列表,但是对于每个x都会调用一次昂贵()两次.是否有一种理解语法可以让您执行此测试,而每个x仅调用一次昂贵的调用?
This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?
推荐答案
如果计算已经很好地捆绑到函数中,那么如何使用filter
和map
?
If the calculations are already nicely bundled into functions, how about using filter
and map
?
result = filter (None, map (expensive, mylist))
如果列表很大,可以使用itertools.imap
.
You can use itertools.imap
if the list is very large.
这篇关于如何有效地过滤Python列表推导中的计算值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!