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