让我告诉你代码中发生了什么:
# Initial position
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# ^
# i
# Remove first
[1, 2, 3, 4, 5, 6, 7, 8, 9]
# ^
# i
# Move next
[1, 2, 3, 4, 5, 6, 7, 8, 9]
# ^
# i
# Remove first
[2, 3, 4, 5, 6, 7, 8, 9]
# ^
# i
# Move next
[2, 3, 4, 5, 6, 7, 8, 9]
# ^
# i
# And so on...
[4, 5, 6, 7, 8, 9]
# ^
# i
# Remove first
[5, 6, 7, 8, 9]
# ^
# i
# Move next
# Oops, the end of the list
# The result:
[5, 6, 7, 8, 9]
让我们看看它在后台是如何工作的。首先,我们需要一个迭代器:
# for i in arr:
In [30]: it = iter(arr)
In [31]: it
Out[31]: <listiterator at 0x130f9d0>
我们将调用next(it),直到它引发StopIteration 异常。所以,让我们开始吧:
In [32]: i = next(it)
In [33]: i
Out[33]: 0
哇,我们得到了列表中的第一个元素!让我们看看,如果我们尝试弹出索引为零的元素会发生什么:
# if i in arr:
# print i
# arr.pop(0)
In [34]: i in arr
Out[34]: True
In [35]: print i
0
In [36]: arr.pop(0)
Out[36]: 0
In [37]: arr
Out[37]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
好的,元素已弹出。移动到下一个循环迭代:
In [38]: i = next(it)
In [39]: i
Out[39]: 2
嗯...看起来不错,我们得到了第二个元素。让我们再次弹出第一个!
In [40]: i in arr
Out[40]: True
In [41]: print i
2
In [42]: arr.pop(0)
Out[42]: 1
In [43]: arr
Out[43]: [2, 3, 4, 5, 6, 7, 8, 9]
让我们看看第三次迭代:
In [44]: i = next(it)
In [45]: i
Out[45]: 4
我想,现在很清楚,该循环将有 5 次迭代。在每次迭代中,您将删除第一个元素。而且,正因为如此,您将在迭代时跳过奇数元素。