函数参数打包和解包Python



目前,我有一个这样的函数:

def my_func(*args):
#prints amount of arguments
print(len(args))
#prints each argument
for arg in args:
print(arg)

我想给这个函数添加多个参数,但下面的不适用。它在else后面的星号*上给出了一个语法错误。

my_func(
*(1, 2, 3, 4)
if someBool is True
else *(1, 2)
)

我找到的解决方法是先输入1和2,然后在检查someBool时输入3和4。

my_func(
1, 2,
3 if someBool is True else None,
4 if someBool is True else None
)

我对以上内容很满意,因为我的功能检查为"无",但如果有其他选择,我很乐意感谢他们。

*移动到... if ... else ...:外部

my_func(
*((1, 2, 3, 4)
if someBool is True
else (1, 2))
)

您需要一组额外的括号。此外,您不需要说is True来检查python中的布尔值是否为"truthy",使其成为:my_func(*((1, 2, 3, 4) if someBool else (1, 2)))

最新更新