迭代函数的Python迭代器
问题描述:
所以我必须做以下函数 - >迭代。在第一次调用时,它应该在第三个func.func上返回第二个func的身份。 任何想法如何做到这一点?我试图寻找在ITER和下一个方法BUF失败:(迭代函数的Python迭代器
>>> def double(x):
return 2 * x
>>> i = iterate(double)
>>> f = next(i)
>>> f(3)
3
>>> f = next(i)
>>> f(3)
6
>>> f = next(i)
>>> f(3)
12
>>> f = next(i)
>>> f(3)
24
答
像这样的东西可能:
>>> import functools
>>> def iterate(fn):
def repeater(arg, _count=1):
for i in range(_count):
arg = fn(arg)
return arg
count = 0
while True:
yield functools.partial(repeater, _count=count)
count += 1
>>> i = iterate(double)
>>> f, f2, f3, f4 = next(i), next(i), next(i), next(i)
>>> f(3), f2(3), f3(3), f4(3)
(3, 6, 12, 24)
>>> f(3), f2(3), f3(3), f4(3)
(3, 6, 12, 24)
所以你编写调用原函数的次数的函数指定为参数,并且您预先绑定了计数参数。
非常感谢!您帮了我很多! – 2013-03-13 08:23:36