为什么使用pop-method(或del语句)的for-loop不能迭代所有列表元素 [英] Why does a for-loop with pop-method (or del statement) not iterate over all list elements
问题描述
我是Python新手,尝试使用列表
我正在使用Python 3.2.3(默认,2012年10月19日,20:13:42),Linux2上的[GCC 4.6.3]
以下是我的示例代码
>>> l = [1,2,3,4,5,6]
>>> (l)
...
我期望以下输出
1
[2,3,4,5,6]
2
[3,4,5,6]
3
[4,5,6]
4
[5,6]
5
[6]
6
[]
相反,我得到这个
1
[2,3, 4,5,6]
2
[3,4,5,6]
3
[4,5,6]
for循环在3转之后停止迭代。有人可以解释一下为什么吗?解决方案展开一点(脱字符( ^
) >)在循环index):
your_list = [1,2,3,4,5,6]
弹出第一项后:
your_list = [2,3,4,5,6]
^
现在继续循环:
your_list = [2,3,4, 5,6]
^
现在弹出第一项:
your_list = [3,4,5,6]
$ p
^
现在继续循环:
$ p $your_list = [3,4, 5,6]
^
现在弹出第一项:
your_list = [4,5,6]
^
现在继续循环 - 等等,我们完成了。 : - )
>>> l = [1,2,3,4,5,6]
>>> for x in l:
... l.pop(0)
...
1
2
3
>>>打印l
[4,5,6]
I am new to Python and experimenting with lists I am using Python 3.2.3 (default, Oct 19 2012, 20:13:42), [GCC 4.6.3] on linux2
Here is my samplecode
>>> l=[1,2,3,4,5,6]
>>> for i in l:
... l.pop(0)
... print(l)
...
I would expect the following output
1
[2, 3, 4, 5, 6]
2
[3, 4, 5, 6]
3
[4, 5, 6]
4
[5, 6]
5
[6]
6
[]
Instead I am getting this
1
[2, 3, 4, 5, 6]
2
[3, 4, 5, 6]
3
[4, 5, 6]
The for-loop stops iterating after 3 turns. Can somebody explain why?
Unrolling a bit (the caret (^
) is at the loop "index"):
your_list = [1,2,3,4,5,6]
^
after popping off the first item:
your_list = [2,3,4,5,6]
^
now continue the loop:
your_list = [2,3,4,5,6]
^
Now pop off the first item:
your_list = [3,4,5,6]
^
Now continue the loop:
your_list = [3,4,5,6]
^
Now pop off first item:
your_list = [4,5,6]
^
Now continue the loop -- Wait, we're done. :-)
>>> l = [1,2,3,4,5,6]
>>> for x in l:
... l.pop(0)
...
1
2
3
>>> print l
[4, 5, 6]
这篇关于为什么使用pop-method(或del语句)的for-loop不能迭代所有列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!