Python pop()与pop(0)

2024-04-29 00:39:27 发布

您现在位置:Python中文网/ 问答频道 /正文

所以下面让我很困惑。

#!/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]

也许,我从根本上误解了pop是如何实现的。但我的理解是,它删除列表中给定索引处的项,并返回它。如果未指定索引,则默认为最后一项。因此,在第一个循环中,它应该从列表左侧移除3个项,在第二个循环中,它应该从列表末尾移除3个项。


Tags: inpytest列表forifbinubuntu
3条回答

在遍历列表时,您正在对其进行修改,这会导致混乱。如果您查看第一个元素,将其移除,然后继续查看第二个元素,则您遗漏了一个元素。

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

第一个测试并不奇怪;三个元素在最后被移除。

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

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不会抱怨(与字典不同,字典在迭代过程中不能被修改),但它会导致奇怪的、通常违反直觉的情况,比如这一种。

因为in list或Stack在last-in-first-out[LIFO]中工作,所以使用pop()来删除列表中的最后一个元素

其中aspop(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.)

相关问题 更多 >