例如我有一句话
"He is so .... cool!"
然后我删除所有标点符号并将其列在一个列表中。
["He", "is", "so", "", "cool"]
如何删除或忽略空字符串?
您可以使用filter
, withNone
作为键函数,它过滤掉所有False
ish 元素(包括空字符串)
>>> lst = ["He", "is", "so", "", "cool"]
>>> filter(None, lst)
['He', 'is', 'so', 'cool']
但是请注意,这filter
在 Python 2 中返回一个列表,但在 Python 3 中返回一个生成器。您需要将其转换为 Python 3 中的列表,或使用列表解析解决方案。
False
ish 价值观包括:
False
None
0
''
[]
()
# and all other empty containers
你可以像这样过滤它
orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]
或者你可以使用filter
. 在 python 3filter
中返回一个生成器,从而list()
将它变成一个列表。这也适用于 python 2.7
result = list(filter(None, orig))
您可以使用列表推导:
cleaned = [x for x in your_list if x]
虽然我会使用正则表达式来提取单词:
>>> import re
>>> sentence = 'This is some cool sentence with, spaces'
>>> re.findall(r'(\w+)', sentence)
['This', 'is', 'some', 'cool', 'sentence', 'with', 'spaces']
我会回答你应该问的问题——如何完全避免空字符串。我假设您执行以下操作来获取您的列表:
>>> "He is so .... cool!".replace(".", "").split(" ")
['He', 'is', 'so', '', 'cool!']
关键是你.split(" ")
用来分割空格字符。但是,如果您省略 的参数,则会split
发生这种情况:
>>> "He is so .... cool!".replace(".", "").split()
['He', 'is', 'so', 'cool!']
引用文档:
如果 sep 未指定或为 None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随空格,则结果将在开头或结尾不包含空字符串。
因此,您真的不需要为其他答案而烦恼(Blender 除外,这是一种完全不同的方法),因为 split 可以为您完成这项工作!
>>> from string import punctuation
>>> text = "He is so .... cool!"
>>> [w.strip(punctuation) for w in text.split() if w.strip(punctuation)]
['He', 'is', 'so', 'cool']
您可以使用列表推导非常轻松地过滤掉空字符串:
x = ["He", "is", "so", "", "cool"]
x = [str for str in x if str]
>>> ['He', 'is', 'so', 'cool']
Python 3 返回一个iterator
from filter
,因此应该包含在对 list() 的调用中
str_list = list(filter(None, str_list)) # fastest
lst = ["He", "is", "so", "", "cool"]
lst = list(filter(str.strip, lst))
您可以使用filter
.
a = ["He", "is", "so", "", "cool"]
filter(lambda s: len(s) > 0, a)