嵌套迭代器从嵌套的方法访问变量

2024-10-01 22:40:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个迭代器,在使用另一个迭代器时计算它的长度。 下面是一个我想要实现的工作示例:

from random import random

def randleniter(p):
    while random() < p:
        yield 7

count = 0

def do():
    def countiter(piter):
        global count
        for i in piter:
            count += 1
            yield i
    list(countiter(randiter(0.99))) #simulator for a different method consuming the iterator
    return count

>>> do()
81

但是,如果我打算使用全局变量,我永远不会这样构建它。我想既然我可以用嵌套方法来实现:

^{pr2}$

我可以这样做:

def do():
    count = 0
    def countiter(piter):
        for i in piter:
            count += 1
            yield i
    list(countiter(randiter(0.99)))
    return count

但这会导致UnboundLocalError: local variable 'count' referenced before assignment。当我从countiter内部print locals()时,它不包括count。 我能让countiter访问{}吗?在


Tags: infromimport示例forreturndefcount
1条回答
网友
1楼 · 发布于 2024-10-01 22:40:15

您所描述的内容称为closure,这是一个完全独立于迭代器和生成器的主题。 Python3.x有一个nonlocal关键字(只需在countiter中声明nonlocal count以匹配您想要的行为,在Python2.7中,您必须通过可变对象来模拟它(因为内部函数可以read和{}外部函数变量,而不是{})。在

所以你实际上可以:

def do():
    count = [0,]
    def countiter(iter):
        for i in iter:
            count[0] += 1
            yield i
    list(countiter(randiter(0.99)))
    return count[0]

相关问题 更多 >

    热门问题