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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16099694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:46:00  来源:igfitidea点击:

How to remove empty string in a list?

pythonlist

提问by Alexa Elis

For example I have a sentence

例如我有一个句子

"He is so .... cool!"

Then I remove all the punctuation and make it in a list.

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

["He", "is", "so", "", "cool"]

How do I remove or ignore the empty string?

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

采纳答案by Volatility

You can use filter, with Noneas the key function, which filters out all elements which are Falseish (including empty strings)

您可以使用filter, withNone作为关键功能,它过滤掉所有Falseish元素(包括空字符串)

>>> lst = ["He", "is", "so", "", "cool"]
>>> filter(None, lst)
['He', 'is', 'so', 'cool']

Note however, that filterreturns a list in Python 2, but a generator in Python 3. You will need to convert it into a list in Python 3, or use the list comprehension solution.

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

Falseish values include:

Falseish 值包括:

False
None
0
''
[]
()
# and all other empty containers

回答by msvalkon

You can filter it like this

你可以像这样过滤它

orig = ["He", "is", "so", "", "cool"]
result = [x for x in orig if x]

Or you can use filter. In python 3 filterreturns a generator, thus list()turns it into a list. This works also in python 2.7

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

result = list(filter(None, orig))

回答by jamylak

>>> 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']

回答by Yuushi

You can filter out empty strings very easily using a list comprehension:

您可以使用列表推导非常轻松地过滤掉空字符串:

x = ["He", "is", "so", "", "cool"]
x = [str for str in x if str]
>>> ['He', 'is', 'so', 'cool']

回答by Blender

You can use a list comprehension:

您可以使用列表理解:

cleaned = [x for x in your_list if x]

Although I would use regex to extract the words:

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

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

回答by mchail

You can do this with a filter.

您可以使用filter.

a = ["He", "is", "so", "", "cool"]
filter(lambda s: len(s) > 0, a)

回答by Lauritz V. Thaulow

I'll give you the answer to the question you shouldhave asked -- how to avoid the empty string altogether. I assume you do somethinglike this to get your list:

我会回答你应该问的问题——如何完全避免空字符串。我假设你做这样的事情来获得你的清单:

>>> "He is so .... cool!".replace(".", "").split(" ")
['He', 'is', 'so', '', 'cool!']

The point is that you use .split(" ")to split on space characters. However, if you leave out the argument to split, this happens:

关键是你.split(" ")用来分割空格字符。但是,如果您省略 的参数,则会split发生这种情况:

>>> "He is so .... cool!".replace(".", "").split()
['He', 'is', 'so', 'cool!']

Quoth the docs:

引用文档:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

如果未指定 sep 或为 None ,则应用不同的拆分算法:将连续空格的运行视为单个分隔符,如果字符串有前导或尾随空格,则结果将在开头或结尾不包含空字符串。

So you really don't need to bother with the other answers (except Blender's, which is a totally different approach), because split can do the job for you!

所以你真的不需要打扰其他答案(除了 Blender,这是一种完全不同的方法),因为 split 可以为你完成这项工作!

回答by user702846

Python 3 returns an iteratorfrom filter, so should be wrapped in a call to list()

Python 3 返回一个iteratorfrom filter,因此应该包含在对 list() 的调用中

str_list = list(filter(None, str_list)) # fastest