考虑假设的函数 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]
我可以发誓我在 Python 2.x 标准库的某处看到过类似 repeatcall
的函数,但我找不到它。如果这不是我的梦想,我可以在标准库的什么地方找到它?
PS:我知道自己动手是微不足道的,但我讨厌重新发明轮子,尤其是那些已经在标准库中的轮子。我不是问如何自己动手。
编辑:让它更加明确我不是在问如何编码repeatcall
。
最佳答案
您已经在标准库文档中看到了这一点,而不是标准库本身。
它是来自itertools
recipes 的repeatfunc
:
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))
它允许参数并且(理论上)应该比列表理解表现得更好,因为 func
只需要查找一次。当您实际上没有使用计数器时,repeat
也比 range
更快。
关于python - 重复调用函数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10048916/