Cra*_*mer 0 python for-loop python-3.x
我曾经认为python中的for 循环是这样工作的,它首先通过执行iter(iterable)
then 来创建一个迭代器,然后next(that_new_iterator_object)
当它引发时,StopIteration然后for 循环结束并else阻塞(如果提供),但在这里它的工作方式有所不同
>>> a = [1,2,3,4,5,6,7,8,9]
>>> for i in a:
del a[-1]
print(i)
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
其他数字 6,7,8,9 在哪里 for 循环创建的新迭代器对象和变量 a 不同
在for循环,就像你所描述的作品。但是,列表迭代器的工作原理大致如下:
class ListIterator:
def __init__(self, lst):
self.lst = lst
self.idx = 0
def __iter__(self):
return self
def __next__(self):
if self.idx >= len(self.lst):
raise StopIteration
else:
val = self.lst[self.idx]
self.idx += 1
return val
Run Code Online (Sandbox Code Playgroud)
IOW,迭代器取决于您正在修改的列表。
所以观察:
>>> class ListIterator:
... def __init__(self, lst):
... self.lst = lst
... self.idx = 0
... def __iter__(self):
... return self
... def __next__(self):
... if self.idx >= len(self.lst):
... raise StopIteration
... else:
... val = self.lst[self.idx]
... self.idx += 1
... return val
...
>>> a = list(range(10))
>>> iterator = ListIterator(a)
>>> for x in iterator:
... print(x)
... del a[-1]
...
0
1
2
3
4
>>>
Run Code Online (Sandbox Code Playgroud)