我想创建一个迭代器,在使用另一个迭代器时计算它的长度。 下面是一个我想要实现的工作示例:
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
访问{
您所描述的内容称为}外部函数变量,而不是{})。在
closure
,这是一个完全独立于迭代器和生成器的主题。 Python3.x有一个nonlocal
关键字(只需在countiter中声明nonlocal count
以匹配您想要的行为,在Python2.7中,您必须通过可变对象来模拟它(因为内部函数可以read
和{所以你实际上可以:
相关问题 更多 >
编程相关推荐