Python pop()vs pop(0)

Per*_*pus 9 python stack

所以以下让我感到困惑.

#!/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
Run Code Online (Sandbox Code Playgroud)

结果

ubuntu-vm:~/sandbox$ ./test.py 
[0, 0, 0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

也许,我从根本上误解了pop的实现方式.但我的理解是,它删除列表中给定索引处的项目,并返回它.如果未指定索引,则默认为最后一项.所以看起来在第一个循环中它应该从列表的左边删除3个项目,而在第二个循环中它应该从列表的末尾删除3个项目.

nne*_*neo 16

第一次测试并不令人惊讶; 最后删除了三个元素.

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

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]
   ^
Run Code Online (Sandbox Code Playgroud)

从现在开始,没有遇到零,因此不再删除​​任何元素.


为了避免将来出现混淆,请尝试在迭代列表时不要修改列表.虽然Python不会抱怨(不像字典,在迭代期间无法修改),但它会导致像这样的奇怪且通常违反直觉的情况.


sth*_*sth 6

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

最初排在第二位的元素从未被检查过,因为它在迭代过程中“改变了位置”。


sun*_*raj 6

由于 in list 或 Stack 在后进先出 [LIFO] 中工作,因此pop()使用它删除列表中的最后一个元素

其中 aspop(0)意味着它删除索引中的元素,即列表的第一个元素

根据文档

list.pop([i]):
Run Code Online (Sandbox Code Playgroud)

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.)