Python如何在内部管理“ for”循环? [英] How does Python manage a 'for' loop internally?

查看:67
本文介绍了Python如何在内部管理“ for”循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Python,我开始玩一些代码:

I'm trying to learn Python, and I started to play with some code:

a = [3,4,5,6,7]
for b in a:
    print(a)
    a.pop(0)

输出为:

[3, 4, 5, 6, 7]
[4, 5, 6, 7]
[5, 6, 7]

我知道这不是 的好习惯,当我在它上循环时更改数据结构,但是我想了解Python如何在此管理迭代器

I know that's not a good practice change data structures while I'm looping on it, but I want to understand how Python manage the iterators in this case.

主要问题是:如果我更改 a的状态,它如何知道必须完成循环

The principal question is: How does it know that it has to finish the loop if I'm changing the state of a?

推荐答案

kjaquier和Felix讨论了迭代器协议,我们可以在您的实践中看到它情况:

kjaquier and Felix have talked about the iterator protocol, and we can see it in action in your case:

>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> iterator
<list_iterator object at 0x101231f28>
>>> next(iterator)
1
>>> L.pop()
3
>>> L
[1, 2]
>>> next(iterator)
2
>>> next(iterator)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration

由此我们可以推断出 list_iterator .__ next __ 的代码行为类似于:

From this we can infer that list_iterator.__next__ has code that behaves something like:

if self.i < len(self.list):
    return self.list[i]
raise StopIteration

它不能天真地得到物品。这将引发一个 IndexError ,它会冒泡到顶部:

It does not naively get the item. That would raise an IndexError which would bubble to the top:

class FakeList(object):
    def __iter__(self):
        return self

    def __next__(self):
        raise IndexError

for i in FakeList():  # Raises `IndexError` immediately with a traceback and all
    print(i)

实际上,查看listiter_next rel = nofollow noreferrer> CPython来源(感谢Brian Rodriguez):

Indeed, looking at listiter_next in the CPython source (thanks Brian Rodriguez):

if (it->it_index < PyList_GET_SIZE(seq)) {
    item = PyList_GET_ITEM(seq, it->it_index);
    ++it->it_index;
    Py_INCREF(item);
    return item;
}

Py_DECREF(seq);
it->it_seq = NULL;
return NULL;

尽管我不知道如何返回NULL; 最终转换为 StopIteration

Although I don't know how return NULL; eventually translates into a StopIteration.

这篇关于Python如何在内部管理“ for”循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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