Clo*_*one 1 python list python-3.x
为什么我的代码不会删除列表中的最后一个空元素?
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
for element in templist:
if element == '':
templist.remove(element)
print (templist)
Run Code Online (Sandbox Code Playgroud)
输出:
['hello', 'hi', 'mkay', '']
Run Code Online (Sandbox Code Playgroud)
Ell*_*rts 10
好吧,你总是可以这样做:
new_list = list(filter(None, templist))
Run Code Online (Sandbox Code Playgroud)
因为您正在改变正在迭代的列表.可以把它想象成for循环使用索引进行迭代; 删除元素会减少列表的长度,从而使索引无效> len(list) - 1.
对此的"Pythonic"解决方案是使用列表理解:
templist = ['', 'hello', '', 'hi', 'mkay', '', '']
templist[:] = [item for item in templist if item != '']
Run Code Online (Sandbox Code Playgroud)
这将执行到位去除列表项.
要指出您的错误,请迭代列表的副本,即将您的for语句更改为:
for element in templist[:]:
Run Code Online (Sandbox Code Playgroud)
在迭代列表时更改列表会导致您看到奇怪的结果。
更紧凑的是,您可以使用filter以下方法:
templist = list(filter(None, templist))
Run Code Online (Sandbox Code Playgroud)
当None提供给它时,它只是返回 true 元素(空字符串评估为 false)。
| 归档时间: |
|
| 查看次数: |
25378 次 |
| 最近记录: |