重复调用函数的功能?

kjo*_*kjo 6 python iteration iterator

考虑假设函数repeatcall,它将参数作为无参数可调用func和正整数n,并返回一个列表,其成员是通过执行func() n次数获得的.它支持无限的愚蠢的hijinks流,如:

>>> repeatcall(lambda: id(dict()), 5)
[45789920, 45788064, 45807216, 45634816, 45798640]

>>> urandom = lambda: struct.unpack('Q', open('/dev/urandom').read(8))[0]
>>> repeatcall(urandom, 3)
[3199039843823449742, 14990726001693341311L, 11583468019313082272L]

>>> class Counter(itertools.count): __call__ = itertools.count.next
>>> repeatcall(Counter(100, -2), 4)
[100, 98, 96, 94]
Run Code Online (Sandbox Code Playgroud)

我可以发誓,我已经repeatcall在Python 2.x标准库中看到过像某个函数,但我找不到它.如果我没有梦想这个,我可以在标准库中找到它吗?

PS:我知道推出自己的产品是微不足道的,但我讨厌重新发明轮子,特别是那些已经在标准库中的轮子.我不是在问自己怎么样.

编辑:让我更明确的是我不会问如何编码repeatcall.

agf*_*agf 13

您已经在标准库文档中看到过这种情况,而不是标准库本身.

repeatfunc来自itertools食谱:

def repeatfunc(func, times=None, *args):
    """Repeat calls to func with specified arguments.

    Example:  repeatfunc(random.random)
    """
    if times is None:
        return starmap(func, repeat(args))
    return starmap(func, repeat(args, times))
Run Code Online (Sandbox Code Playgroud)

它允许参数并且(理论上)应该比列表理解更好地执行,因为func只需要查找一次.repeat也比range你实际上没有使用计数器时更快.

  • @jdi 是的,我保留它在标准库中不存在。他记得看过它,因为它在文档中。这就是他的问题的答案。 (2认同)
  • @jdi 90%被包括在内,所以人们不必点击查看`itertools`文档就可以看到我在说什么.所以答案应该尽可能地独立,而不是依靠外部资源. (2认同)