【发布时间】:2019-04-14 18:21:21
【问题描述】:
目前,我有这样的功能:
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语句? -
我有一个函数接受 2、4 或任何偶数个参数。把它放在一个函数中使它(对我来说)更容易检查和理解。我会把它放在外面,但我更喜欢三元运算符。感谢您的建议:D
标签: python python-3.x function ternary-operator