Python 带三元运算符的可选参数
我有一个函数Python 带三元运算符的可选参数,python,arguments,optional,ternary-operator,Python,Arguments,Optional,Ternary Operator,我有一个函数f,它可以接受不同数量的参数,如下所示: f = f_5_args if five else f_4_args fargs = [x1, x2, x3, x4] if five: fargs.append(x5) result = f_5_args(*fargs) else: result = f_4_args(*fargs) 要调用f,我目前正在执行以下操作: if five: result = f(x1, x2, x3, x4, x5) else:
f
,它可以接受不同数量的参数,如下所示:
f = f_5_args if five else f_4_args
fargs = [x1, x2, x3, x4]
if five:
fargs.append(x5)
result = f_5_args(*fargs)
else:
result = f_4_args(*fargs)
要调用f
,我目前正在执行以下操作:
if five:
result = f(x1, x2, x3, x4, x5)
else:
result = f(x1, x2, x3, x4)
有没有更好的方法调用f
,也可以使用三元运算符或类似的东西?在其他语言(如Lua)中,我可以执行以下操作:
result = f(x1, x2, x3, x4, x5 if five else None)
但是我在python中找不到类似的东西
编辑:当然我可以做:
result = f(x1, x2, x3, x4, x5) if five else f(x1, x2, x3, x4)
但在我的情况下,x_i是一些相对较长的表达式,因此我宁愿不写两次。我可以将它们存储在一些变量中并执行此操作,但我想知道是否有更好的方法。您可以执行以下操作:
result = f(*(filter(None, (x1, x2, x3, x4, x5 if five else None))))
请注意,此解决方案消除了所有的假值和零值以及
None
s,因此如果适合您的用例,请使用它。您可以这样做:
f = f_5_args if five else f_4_args
fargs = [x1, x2, x3, x4]
if five:
fargs.append(x5)
result = f_5_args(*fargs)
else:
result = f_4_args(*fargs)
这样可以避免将所有函数参数写两次。如果您有参数列表,可以使用切片使其更加简洁:
args = [x1, x2, x3, x4, x5]
result = f(*args) if five else f(*args[:4])
但使用接受任意数量位置参数的函数可能更容易:
def f45(*args):
if len(args) == 5:
# do something
elif len(args) == 4:
# do something else
什么是
f_5_args
和f_4_args
?它们是分别(严格地)接受5个和4个参数的两个函数。如果某个参数x
有一个虚假值会怎么样?是的,我的解决方案将所有虚假值和零值与None
s一起消除。这显然不是一种将参数传递给函数的pythonic方式