擅长:python、mysql、java
<p>每当我看到<code>iter</code>有2个参数时,我都需要从头开始查阅文档,以确定到底发生了什么。正因为如此,我可能会自己动手:</p>
<pre><code>def call_forever(callback):
while True:
yield callback()
</code></pre>
<hr/>
<p>或者,正如Jon Clements在评论中所述,您可以使用<code>itertools.repeatfunc</code>方法,它也允许您将参数传递给函数:</p>
^{pr2}$
<p>虽然我认为函数签名<code>def repeatfunc(func,times=None,*args)</code>有点尴尬。我更喜欢将元组作为args传递(在我看来,它更显式,“显式优于隐式”):</p>
<pre><code>import itertools as it
def repeatfunc(func, args=(),times=None):
"""
Repeat calls to func with specified arguments.
Example: repeatfunc(random.random)
"""
if times is None:
return it.starmap(func, it.repeat(args))
return it.starmap(func, it.repeat(args, times))
</code></pre>
<p>它可以被称为:</p>
<pre><code>repeatfunc(func,(arg1,arg2,...,argN),times=4) #repeat 4 times
repeatfunc(func,(arg1,arg2,...)) #repeat infinitely
</code></pre>
<p>而不是来自<code>itertools</code>的普通版本:</p>
<pre><code>repeatfunc(func,4,arg1,arg2,...) #repeat 4 times
repeatfunc(func,None,arg1,arg2,...) #repeat infinitely
</code></pre>