2014-06-11 74 views
5

所以下面是令我困惑的。Python pop()vs pop(0)

#!/usr/bin/python 

test = [0, 0, 0, 1, 2, 3, 4, 5, 6] 
test1 = [0, 0, 0, 1, 2, 3, 4, 5, 6] 

for _dummy in test: 
    if(_dummy == 0): 
     test.pop() 
for _dummy in test1: 
    if(_dummy == 0): 
     test1.pop(0) 

print test 
print test1 

结果

ubuntu-vm:~/sandbox$ ./test.py 
[0, 0, 0, 1, 2, 3] 
[0, 1, 2, 3, 4, 5, 6] 

也许,我从根本上误解的流行是如何实现的。但我的理解是,它会删除列表中给定索引处的项目,并将其返回。如果没有指定索引,则默认为最后一个项目。所以看起来,在第一个循环中它应该从列表的左边移除3个项目,而在第二个循环中它应该从列表的末尾移除3个项目。

+0

这在我的机器上完美地工作。我正在使用Python 2.7.6 – XrXrXr

+0

在遍历它时不能对列表进行变异。 – univerio

+0

我在两个不同的系统上试过这个。其一,是由运行python 2.6的大学提供的IDE。另一个是在我的虚拟机ubuntu上运行2.7.4。嗯。 – PerryDaPlatypus

回答

12

第一次测试并不奇怪;三个元素被删除。

第二个测试有点令人惊讶。只有两个元素被删除。为什么?

Python中的列表迭代本质上包含一个递增索引到列表中。当你删除一个元素时,你将右侧的所有元素都转移过来。这可能会导致索引指向不同的元素。

例证:

start of loop 
[0,0,0,1,2,3,4,5,6] 
^ <-- position of index 

delete first element (since current element = 0) 
[0,0,1,2,3,4,5,6] 
^ 

next iteration 
[0,0,1,2,3,4,5,6] 
^

delete first element (since current element = 0) 
[0,1,2,3,4,5,6] 
^

,从现在起没有零点遇到,所以没有更多的元素被删除。


为了避免将来发生混淆,请尽量不要在迭代它们时修改列表。尽管Python不会抱怨(不像字典,它在迭代过程中不能被修改),但它会导致奇怪的并且通常是违反直觉的情况,比如这个。

+0

fyi,当我运行它时,最后的指针指向2 – Fabricator

+0

@ user3678068:指针?什么指针?循环从我一路走到最后的地方运行,并且在此之后不修改列表(因为它从不会看到更多的零)。 – nneonneo

+0

我的意思是“指数的位置”指向2而不是1 – Fabricator

4

您在修改列表时正在迭代它们,导致混淆。如果你看第一个元素,删除它,然后继续查看第二个元素,那么你错过了一个元素。

最初处于第二位的元素从未被检查,因为它在迭代期间“改变了位置”。

+0

非常感谢! – PerryDaPlatypus

1

因为在列表或栈工作在后进先出[LIFO]所以pop()使用它删除最后一个元素的列表

凡为pop(0)意味着它删除元素是第一元素的索引名单

按照该文件

list.pop([i]): 

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)