在相当长的一段时间里,我一直试图想出一种方法来遍历列表并删除我当前的项目.我似乎无法像我希望的那样工作.它只循环一次,但我希望它循环2次.当我删除删除行 - 它循环2次.
a = [0, 1]
for i in a:
z = a
print z.remove(i)
Run Code Online (Sandbox Code Playgroud)
输出:
[1]
Run Code Online (Sandbox Code Playgroud)
我期待的输出:
[1]
[0]
Run Code Online (Sandbox Code Playgroud)
你在迭代它时更改列表 - z = a不进行复制,只是指向z相同的位置a点.
尝试
for i in a[:]: # slicing a list makes a copy
print i # remove doesn't return the item so print it here
a.remove(i) # remove the item from the original list
Run Code Online (Sandbox Code Playgroud)
要么
while a: # while the list is not empty
print a.pop(0) # remove the first item from the list
Run Code Online (Sandbox Code Playgroud)
如果您不需要显式循环,则可以使用列表推导删除与条件匹配的项:
a = [i for i in a if i] # remove all items that evaluate to false
a = [i for i in a if condition(i)] # remove items where the condition is False
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
520 次 |
| 最近记录: |