for循环实际上如何在python中工作

for循环实际上如何在python中工作

问题描述:

我曾经认为python中的 for-loop 可以像这样工作 它首先通过执行iter(iterable)来创建迭代器 然后执行next(that_new_iterator_object) 当它升高StopIteration时, for-循环结束并转到else块(如果提供) 但这里的工作方式有所不同

I used to thought that for-loop in python work like this it first makes an iterator by doing iter(iterable) then does next(that_new_iterator_object) and when it raises StopIteration then for-loop ends and goes to else block (if provided) but here it is working differently

>>> 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循环创建的新迭代器对象与变量a不同

where are the other numbers 6,7,8,9 the new iterator object that for-loop creates and variable a is different

for循环的功能与您描述的一样.但是,大致是列表迭代器的工作原理:

The for loop works just as you described. However, here is how a list iterator works, roughly:

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,迭代器取决于您要修改的列表.

IOW, the iterator depends on the list, which you are modifying.

所以请注意:

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