“times”的循环如果“times”不是“None”else循环

2024-04-19 16:54:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个形式函数

def foo(times=None):
    iterator = range(times) if times else itertools.count()
    for _ in iterator:
        # do stuff

有没有一个更具Python或优雅的方式来实现这一点?你知道吗


Tags: 函数innoneforiffoodefcount
1条回答
网友
1楼 · 发布于 2024-04-19 16:54:10

首先,如果您没有使用变量,就像您使用_作为名称一样,请使用^{},因为它更像您想要做的事情,而且效率非常略高。你知道吗

如果您已经在使用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。你知道吗

相关问题 更多 >