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()
. And with itertools.ifilter()
, the whole thing could be turned into a generator.
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.