问题描述
我是 Python 新手,正在尝试使用列表我在 linux2 上使用 Python 3.2.3(默认,2012 年 10 月 19 日,20:13:42),[GCC 4.6.3]
这是我的示例代码
>>>l=[1,2,3,4,5,6]>>>对于我在 l:... l.pop(0)...打印(升)...我希望得到以下输出
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 圈后停止迭代.有人能解释一下原因吗?
展开一点(插入符号 (^
) 位于循环索引"处):
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]^
现在继续循环:
your_list = [3,4,5,6]^
现在弹出第一项:
your_list = [4,5,6]^
现在继续循环——等等,我们完成了.:-)
>>>l = [1,2,3,4,5,6]>>>对于 x 中的 l:... l.pop(0)...123>>>打印 l[4, 5, 6]I am new to Python and experimenting with listsI 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 方法(或 del 语句)的 for 循环不遍历所有列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!