[英]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)
我想在此函數中添加多個參數,但以下內容對我不起作用。 否則,它在星號*上給出語法錯誤。
my_func(
*(1, 2, 3, 4)
if someBool is True
else *(1, 2)
)
我發現的解決方法是先放入1和2,然后再放入3和4,同時檢查someBool。
my_func(
1, 2,
3 if someBool is True else None,
4 if someBool is True else None
)
我對上面的命令很滿意,因為我的函數檢查None,但是如果有其他選擇,我將很高興感謝他們。
如果將*
移至... if ... else ...
之外... if ... else ...
:
my_func(
*((1, 2, 3, 4)
if someBool is True
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.