[英]Function Argument Packing And Unpacking Python
Currently, I have a function like so: 目前,我有一个类似的功能:
def my_func(*args):
#prints amount of arguments
print(len(args))
#prints each argument
for arg in args:
print(arg)
I want to put multiple arguments through to this function, but the following doesn't work for me. 我想在此函数中添加多个参数,但以下内容对我不起作用。 It gives out a syntax error on the asterisk * after the else.
否则,它在星号*上给出语法错误。
my_func(
*(1, 2, 3, 4)
if someBool is True
else *(1, 2)
)
The workaround I found puts 1 and 2 in first and then puts 3 and 4 while checking for someBool. 我发现的解决方法是先放入1和2,然后再放入3和4,同时检查someBool。
my_func(
1, 2,
3 if someBool is True else None,
4 if someBool is True else None
)
I am fine with the above as my function checks for None but if there is an alternative I would gladly thank them. 我对上面的命令很满意,因为我的函数检查None,但是如果有其他选择,我将很高兴感谢他们。
Move the *
to outside the ... if ... else ...
: 如果将
*
移至... if ... else ...
之外... if ... else ...
:
my_func(
*((1, 2, 3, 4)
if someBool is True
else (1, 2))
)
You need an extra set of parenthesis. 您需要额外的括号。 Also, you don't need to say
is True
to check if a Boolean is "truthy" in python, making it: my_func(*((1, 2, 3, 4) if someBool else (1, 2)))
. 另外,您不需要说
is True
可以检查python中的布尔值是否“真实”,从而使其成为: my_func(*((1, 2, 3, 4) if someBool else (1, 2)))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.