2024-04-19 16:54:10 发布
网友
假设我有一个形式函数
def foo(times=None): iterator = range(times) if times else itertools.count() for _ in iterator: # do stuff
有没有一个更具Python或优雅的方式来实现这一点?你知道吗
首先,如果您没有使用变量,就像您使用_作为名称一样,请使用^{},因为它更像您想要做的事情,而且效率非常略高。你知道吗
_
如果您已经在使用itertools.repeat,请使用第二个times参数:
itertools.repeat
times
def foo(*times): for _ in itertools.repeat(None, *times): # do stuff
如果不想弄坏签名,可以这样做:
def foo(times=None): for _ in itertools.repeat(*((None, times) if times is not None else (None,))): # do stuff
它看起来不那么优雅,但是可以防止意外地提供太多arg。你知道吗
首先,如果您没有使用变量,就像您使用} ,因为它更像您想要做的事情,而且效率非常略高。你知道吗
_
作为名称一样,请使用^{如果您已经在使用
itertools.repeat
,请使用第二个times
参数:如果不想弄坏签名,可以这样做:
它看起来不那么优雅,但是可以防止意外地提供太多arg。你知道吗
相关问题 更多 >
编程相关推荐