[英]Why does a comma appear in the output after the string is used in unpacking in a function?
def func(*n):
print(n)
func(1,2,3,4)
func(*(1,2,3))
func((1,2,3,'hey'))
func(('hey',1))
output:
(1, 2, 3, 4)
(1, 2, 3)
((1, 2, 3, 'hey'),)
(('hey', 1),)
當字符串被添加到參數時,逗號出現在元組之后。
您看到 a ,
after 的原因是因為()
是一個函數調用,其中(some_object,)
是一個元組。
>>> tuple()
()
>>> tuple([None])
(None,)
當您為最后兩個函數調用傳遞參數時,請注意雙(())
func((1,2,3,'hey'))
func(('hey',1))
所以你傳遞的是最后兩個的元組。 查看每個類型
>>> type(('test'))
<class 'str'>
>>> type(('test', 1))
<class 'tuple'>
如果您不想要尾隨逗號,請刪除 args 周圍的額外()
這種行為是預期的:您傳遞給底部兩個示例中的函數的元組表示可變參數*args
元組中的第一個參數(名稱無關緊要,您使用了*n
)。 *args
的目的是創建一個包含傳遞給函數的所有非關鍵字參數的元組。
創建單元素元組時總是會打印一個尾隨逗號以將其區分為元組。 在后兩種情況下,您有一個單元素args
元組,其中一個 4 或 2 元素元組作為其唯一元素。
您的句子“當將字符串添加到參數時,元組后出現逗號”是不正確的——您從調用中刪除了解包運算符*
,它不再將元組扁平化為變量參數,因此字符串與它無關。 即使您將數字作為唯一參數傳遞,您仍然會得到懸掛逗號:
>>> def f(*args): print(args)
...
>>> f(1)
(1,) # `args` tuple contains one number
>>> f(1, 2)
(1, 2) # `args` tuple contains two numbers
>>> f((1, 2))
((1, 2),) # two-element tuple `(1, 2)` inside single-element `args` tuple
>>> f((1,))
((1,),) # single-element tuple `(1,)` inside single-element `args` tuple
>>> f(*(1,)) # unpack the tuple in the caller, same as `f(1)`
(1,)
>>> f(*(1,2)) # as above but with 2 elements
(1, 2)
>>> f((1)) # without the trailing comma, `(1)` resolves to `1` and is not a tuple
(1,)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.