我想创建一个迭代器,在使用另一个迭代器时计算它的长度。 这是我想要实现的目标的一个工作示例:
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
但是,如果我打算使用全局变量,我永远不会像这样构建它。我想,因为我可以使用嵌套方法来做到这一点:
def make_adder(x):
def add(y):
return x + y
return add
我可以做到这一点:
def do():
count = 0
def countiter(piter):
for i in piter:
count += 1
yield i
list(countiter(randiter(0.99)))
return count
但这会导致UnboundLocalError:赋值前引用了局部变量“count”
。当我从 countiter
内部 print locals()
时 - 它不包括 count
。
我可以以某种方式让 countiter
访问 count
吗?
最佳答案
您所描述的内容称为闭包
,这是一个完全独立于迭代器和生成器的主题。
Python3.x 有 nonlocal
关键字(只需在 countiter 中声明 nonlocal count
来匹配您想要的行为,在 python 2.7 中,您必须通过可变对象来模拟它(因为内部函数可以读取
和变异
外部函数变量,但不能分配
给它们。
所以你实际上可以这样做:
def do():
count = [0,]
def countiter(iter):
for i in iter:
count[0] += 1
yield i
list(countiter(randiter(0.99)))
return count[0]
关于python - 嵌套迭代器从嵌套的方法访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24146975/