首页 > 解决方案 > for-loop 在 python 中是如何工作的

问题描述

我曾经认为python中的for循环iter(iterable) 这样工作next(that_new_iterator_object)StopIterationelse

>>> a = [1,2,3,4,5,6,7,8,9]
>>> for i in a:
        del a[-1]
        print(i)

1
2
3
4
5

其他数字在哪里 6,7,8,9 for-loop 创建的新迭代器对象和变量 a 不同

标签: pythonpython-3.xfor-loop

解决方案


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

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

推荐阅读