Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我需要使用[f(char) for char in string]语法从 python 中的字符串构建一个列表,并且我希望能够忽略(不插入列表中)f(x) 的值等于None.
[f(char) for char in string]
None
我怎样才能做到这一点 ?
我们可以创建一个“子查询”。
[r for r in (f(char) for char in string) if r is not None]
如果您也允许忽略所有 False 值(0、False、None 等),则filter可以使用:
filter
filter(None, (f(char) for char in string) ) # or, using itertools.imap, filter(None, imap(f, string))