简体   繁体   English

Python列表理解:测试函数返回

[英]Python list comprehension: test function return

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

so? 所以?

[foo(x) for x in range(10) if ??? ]

How about 怎么样

filter(None, map(foo, range(10)))

If you don't want to keep the intermediate list, replace map() with itertools.imap() . 如果您不想保留中间列表,请将map()替换为itertools.imap() And with itertools.ifilter() , the whole thing could be turned into a generator. 并通过itertools.ifilter() ,整个事情可以变成一个生成器。

itertools.ifilter(None, itertools.imap(foo, range(10)))

Just make a generator to compute the values and build the filtered list from the generator afterwards. 只需生成一个生成器来计算值,然后再从生成器中构建过滤列表。

Example: 例:

# create generator via generator expression
results = (foo(x) for x in xrange(10))
# build result list, not including falsy values
filtered_results = [i for i in results if i]

For reference: 以供参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM