for循环实际上如何在python中工作 [英] How does for-loop actually work in python

查看:78
本文介绍了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
>>>

这篇关于for循环实际上如何在python中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆