如何删除列表中的空字符串?

Ale*_*lis 17 python list

例如,我有一个句子

"He is so .... cool!"
Run Code Online (Sandbox Code Playgroud)

然后我删除所有标点符号并将其放入列表中.

["He", "is", "so", "", "cool"]
Run Code Online (Sandbox Code Playgroud)

如何删除或忽略空字符串?

Vol*_*ity 39

您可以使用filterwith None作为键函数,过滤掉所有Falseish的元素(包括空字符串)

>>> lst = ["He", "is", "so", "", "cool"]
>>> filter(None, lst)
['He', 'is', 'so', 'cool']
Run Code Online (Sandbox Code Playgroud)

但请注意,它filter返回Python 2中的列表,但是Python 3中的生成器.您需要将其转换为Python 3中的列表,或使用列表推导解决方案.

Falseish值包括:

False
None
0
''
[]
()
# and all other empty containers
Run Code Online (Sandbox Code Playgroud)

  • 但要小心,因为这将返回Python 2中的`list`和Python 3中的`generator`. (10认同)
  • 如果你有'['']`会发生什么? (2认同)

msv*_*kon 20

你可以像这样过滤它

orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]
Run Code Online (Sandbox Code Playgroud)

或者你可以使用filter.在python 3中filter返回一个生成器,从而list()将其转换为一个列表.这也适用于python 2.7

result = list(filter(None, orig))
Run Code Online (Sandbox Code Playgroud)


Ble*_*der 7

您可以使用列表理解:

cleaned = [x for x in your_list if x]
Run Code Online (Sandbox Code Playgroud)

虽然我会使用正则表达式来提取单词:

>>> import re
>>> sentence = 'This is some cool sentence with,    spaces'
>>> re.findall(r'(\w+)', sentence)
['This', 'is', 'some', 'cool', 'sentence', 'with', 'spaces']
Run Code Online (Sandbox Code Playgroud)