函数参数打包和解包 Python
Function Argument Packing And Unpacking 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
)
我对上面的内容没问题,因为我的函数会检查 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)))
.
目前,我有这样一个功能:
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
)
我对上面的内容没问题,因为我的函数会检查 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)))
.