Python 从列表中删除所有空元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40598248/
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
Removing all empty elements from a list
提问by Clone
Why does my code not remove the last empty element in the list?
为什么我的代码没有删除列表中的最后一个空元素?
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
for element in templist:
if element == '':
templist.remove(element)
print (templist)
Output:
输出:
['hello', 'hi', 'mkay', '']
回答by Elliot Roberts
Well, you could always just do this:
好吧,你总是可以这样做:
new_list = list(filter(None, templist))
回答by mhawke
Because you are mutating the list that is being iterating over. Think of it as if the for loop is iterating using an index; removing elements reduces the length of the list thereby invalidating indices > len(list) - 1
.
因为您正在改变正在迭代的列表。把它想象成 for 循环正在使用索引进行迭代;删除元素会减少列表的长度,从而使索引 > 无效len(list) - 1
。
The "Pythonic" solution to this is to use a list comprehension:
对此的“Pythonic”解决方案是使用列表理解:
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
templist[:] = [item for item in templist if item != '']
This performs in placeremoval of items from the list.
这会从列表中就地删除项目。
回答by Dimitris Fasarakis Hilliard
To point out your error, by iterating through a copy of the list, i.e changing your for
statement to:
要指出您的错误,请遍历列表的副本,for
即将您的语句更改为:
for element in templist[:]:
Altering a list while you iterate over it leads to the odd results you see.
在迭代列表时更改列表会导致您看到的奇怪结果。
More compactly, you could use filter
for this:
更简洁地,您可以使用filter
:
templist = list(filter(None, templist))
when None
is supplied to it, it simply returns elements that are true (empty strings evaluate to false).
当None
提供给它时,它只返回为真的元素(空字符串计算为假)。
回答by computeriscomputer
You could make a new list called wordGrabber
for example and instead of removing the blanks you could populate your new list with content
您可以创建一个名为wordGrabber
例如的新列表,而不是删除空白,您可以使用内容填充新列表
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
for element in templist:
if element != '':
wordGrabber.append(element)
print (wordGrabber)