【问题标题】:Python iterator that iterates a function迭代函数的 Python 迭代器
【发布时间】:2013-03-12 15:49:13
【问题描述】:

所以我必须使以下函数 -> 迭代。在第一次调用时,它应该在第二个 func 和第三个 func.func 上返回标识。 知道怎么做吗?我尝试查看 iternext 方法 buf failed: (

>>> 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

【问题讨论】:

    标签: python iteration


    【解决方案1】:

    可能是这样的:

    >>> 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)
    

    所以你编写了一个函数,它调用原始函数的次数指定为参数,并且你预先绑定了 count 参数。

    【讨论】:

    • 非常感谢!你帮了我很多!
    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 2012-11-18
    • 2013-05-20
    • 1970-01-01
    • 2015-01-01
    • 2021-10-05
    • 2011-10-20
    相关资源
    最近更新 更多