[英]How to remove empty string in a list?
例如我有一个句子
"He is so .... cool!"
然后我删除所有标点符号并将其放入列表中。
["He", "is", "so", "", "cool"]
如何删除或忽略空字符串?
您可以使用filter
,以None
作为关键函数,它过滤掉所有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 3 filter
返回一个生成器,因此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 从filter
返回一个iterator
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.