2024-05-13 12:51:36 发布
网友
例如我有一句话
"He is so .... cool!"
然后我删除所有标点符号并将其列在列表中。
["He", "is", "so", "", "cool"]
如何删除或忽略空字符串?
你可以这样过滤
orig = ["He", "is", "so", "", "cool"] result = [x for x in orig if x]
或者可以使用filter。在python 3中,filter返回一个生成器,因此list()将其转换为一个列表。这在Python2.7中也适用
filter
list()
result = list(filter(None, orig))
您可以使用^{},使用None作为键函数,它过滤掉所有类似False的元素(包括空字符串)
None
False
>>> lst = ["He", "is", "so", "", "cool"] >>> filter(None, lst) ['He', 'is', 'so', 'cool']
但是,请注意,filter在Python 2中返回一个列表,而在Python 3中返回一个生成器。您需要在Python 3中将其转换为列表,或者使用列表理解解决方案。
Falseish值包括:
False None 0 '' [] () # and all other empty containers
您可以使用列表理解:
cleaned = [x for x in your_list if x]
尽管我会使用regex来提取单词:
>>> import re >>> sentence = 'This is some cool sentence with, spaces' >>> re.findall(r'(\w+)', sentence) ['This', 'is', 'some', 'cool', 'sentence', 'with', 'spaces']
你可以这样过滤
或者可以使用
filter
。在python 3中,filter
返回一个生成器,因此list()
将其转换为一个列表。这在Python2.7中也适用您可以使用^{} ,使用
None
作为键函数,它过滤掉所有类似False
的元素(包括空字符串)但是,请注意,
filter
在Python 2中返回一个列表,而在Python 3中返回一个生成器。您需要在Python 3中将其转换为列表,或者使用列表理解解决方案。False
ish值包括:您可以使用列表理解:
尽管我会使用regex来提取单词:
相关问题 更多 >
编程相关推荐