问题描述
a = [0,1,2,3,4,5]对于 a 中的 b:打印 ":"+str(b)a.pop(0)
认为这可以按顺序遍历整个列表及其所有项目,我运行了此代码并期望如此.
:00:11:22:33:44:55
相反,我得到了这个:
:00:21:42
现在我明白为什么会这样了,但这是否是 python 中的错误?它不应该仍然遍历所有原始对象而不是当前列表的长度吗?为什么这没有抛出越界错误?IE:它不应该仍然完成:
:00:12:24:3错误:4错误:5错误
您正在遍历列表并同时更改它.通过使用 .pop()
,您可以缩短列表,但不会更新迭代器指针.
改为使用副本:
for b in list(a):
或
for b in a[:]:
其中 [:]
切片符号返回列表副本.
另一种方法是使用 while
循环:
while a:打印 a.pop(0)
因为空列表测试为布尔值 False
.
python for
循环使用它的参数作为迭代器,它本身不保留索引.for
循环无法知道"您删除了元素.相反,它是保持该指针的 list()
迭代器:
那个迭代器保存一个计数器,每次你在迭代器上调用 next()
时,它都会给你下一个索引处的值,不管那个值是什么,直到计数器等于列表的当前长度.
a = [0,1,2,3,4,5]
for b in a:
print ":"+str(b)
a.pop(0)
Thinking that this would work in order going through the entire list and all its items I ran this code and expected this.
:0
0
:1
1
:2
2
:3
3
:4
4
:5
5
Instead I got this:
:0
0
:2
1
:4
2
Now I understand why this happened but is this an error in python? Shouldn't it still go through all of the original objects instead of the length of the current list? And why did this not throw and out of bounds error?IE: Shouldn't it still have done:
:0
0
:1
2
:2
4
:3
Error
:4
Error
:5
Error
You are looping over a list and altering it at the same time. By using .pop()
you are shortening the list, but the iterator pointer is not updated.
Use a copy instead:
for b in list(a):
or
for b in a[:]:
where the [:]
slice notation returns a list copy.
Another approach would be to use a while
loop instead:
while a:
print a.pop(0)
because an empty list tests as boolean False
.
The python for
loop uses it's argument as an iterator, it does not itself keep an index. There is no way for the for
loop to 'know' you removed elements. Instead, it's the list()
iterator that keeps that pointer:
>>> a = [0,1,2,3,4,5]
>>> itera = iter(a)
>>> itera.next() # index 0 -> a[0] is 0
0
>>> a.pop(0)
0
>>> a
[1,2,3,4,5]
>>> itera.next() # index 1 -> a[1] is 2
2
That iterator keeps a counter, and every time you call next()
on the iterator it'll give you the value at the next index, whatever that value may be, until the counter is equal to the current lenght of the list.
这篇关于Python For 循环列表有趣的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!