问题
I need to build a list from a string in python using the [f(char) for char in string] syntax and I would like to be able to ignore (not insert in the list) the values of f(x) which are equal to None.
How can I do that ?
回答1:
We could create a "subquery".
[r for r in (f(char) for char in string) if r is not None]
If you allow all False values (0, False, None, etc.) to be ignored as well, filter could be used:
filter(None, (f(char) for char in string) )
# or, using itertools.imap,
filter(None, imap(f, string))
来源:https://stackoverflow.com/questions/3900215/ignore-an-element-while-building-list-in-python