Python列表理解:测试函数返回 [英] Python list comprehension: test function return
本文介绍了Python列表理解:测试函数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以测试列表(或字典)理解中的函数返回?我想避免这样写:
Is there a way to test the return of a function in a list (or dict) comprehension? I'd like to avoid writing that:
lst = []
for x in range(10):
bar = foo(x)
if bar:
lst.append(bar)
并使用列表理解.显然,我不想写:
and use a list comprehension instead. Obviously, I don't want to write:
[foo(x) for x in range(10) if foo(x)]
是吗?
[foo(x) for x in range(10) if ??? ]
推荐答案
如何
filter(None, map(foo, range(10)))
如果您不想保留中间列表,请将map()
替换为 itertools.ifilter()
,整个事情就可以变成发电机.
If you don't want to keep the intermediate list, replace map()
with itertools.imap()
. And with itertools.ifilter()
, the whole thing could be turned into a generator.
itertools.ifilter(None, itertools.imap(foo, range(10)))
这篇关于Python列表理解:测试函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文