为什么我的代码没有删除列表中的最后一个空元素?
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
for element in templist:
if element == '':
templist.remove(element)
print (templist)
输出:
['hello', 'hi', 'mkay', '']
为什么我的代码没有删除列表中的最后一个空元素?
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
for element in templist:
if element == '':
templist.remove(element)
print (templist)
输出:
['hello', 'hi', 'mkay', '']
嗯,你可以总是这样做:
new_list = list(filter(None, templist))
<filter object at 0x7ff4fcdff6d8>
。 - Clonelist()
中。在Python 3中,filter()返回一个过滤器对象,而在Python 2中,filter返回一个列表。因此,在Python 3中,您需要执行list(filter())
。 - Henry C Wong因为您正在改变被迭代的列表。可以将for循环想象成使用索引进行迭代; 删除元素会减少列表的长度,从而使索引> len(list)-1
无效。
这个问题的"Pythonic"解决方案是使用列表推导式:
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
templist[:] = [item for item in templist if item != '']
这将对列表进行就地删除操作。
[item for item in templist if item]
足够了。空字符串会被视为假。 - TemporalWolf0
和None
不是_空的_. - mhawke" "
,在 item != ''
后添加 and not item.isspace()
。当字符串仅由空格(空白字符)组成时,str.isspace()
返回 True
,但当字符串完全为空时不返回 True
。 - j307for
语句更改为:for element in templist[:]:
在迭代列表时修改它会导致你看到的奇怪结果。
更紧凑的方式是,你可以使用filter
:
templist = list(filter(None, templist))
当给它传递None
时,它只会返回那些为真的元素(空字符串被评估为假)。
wordGrabber
的新列表,然后不需要删除空格,而是将内容填充到你的新列表中。templist = ['', 'hello', '', 'hi', 'mkay', '', '']
for element in templist:
if element != '':
wordGrabber.append(element)
print (wordGrabber)
templist[:]
。 - Steven Rumbalski