我们假设,
g = ['1', '', '2', '', '3', '', '4', '']
Run Code Online (Sandbox Code Playgroud)
我想''从g中删除所有,我必须得到
g = ['1', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)
>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> filter(None, g)
['1', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)
Help on built-in function filter in module `__builtin__`: filter(...) filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.
如果您愿意,也可以使用列表推导
>>> [x for x in g if x!=""]
['1', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)
如果列表是所有字符串,请在if语句中使用空序列为false的事实:
>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> [x for x in g if x]
['1', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)
否则,请使用 [x for x in g if x != '']