Python 为什么在函数解包时使用字符串后,输出中会出现逗号?
将字符串添加到参数时,元组后面会出现逗号。之所以在元组后面出现Python 为什么在函数解包时使用字符串后,输出中会出现逗号?,python,python-3.x,parameter-passing,variadic-functions,Python,Python 3.x,Parameter Passing,Variadic Functions,将字符串添加到参数时,元组后面会出现逗号。之所以在元组后面出现,,是因为()是一个函数调用,其中(某个对象,)是元组 output: (1, 2, 3, 4) (1, 2, 3) ((1, 2, 3, 'hey'),) (('hey', 1),) 当您为最后两个函数调用传递参数时,请注意双精度(()) 因此,您传递的是最后两个的元组。请参见每种类型 func((1,2,3,'hey')) func(('hey',1)) >>类型(('test')) >>>类型((‘测试’,1)) 如果您不
,
,是因为()
是一个函数调用,其中(某个对象,)
是元组
output:
(1, 2, 3, 4)
(1, 2, 3)
((1, 2, 3, 'hey'),)
(('hey', 1),)
当您为最后两个函数调用传递参数时,请注意双精度(())
因此,您传递的是最后两个的元组。请参见每种类型
func((1,2,3,'hey'))
func(('hey',1))
>>类型(('test'))
>>>类型((‘测试’,1))
如果您不需要尾随逗号,则删除args周围多余的
(
)此行为是预期的:下面两个示例中传递到函数中的元组表示变量*args
元组中的第一个参数(名称无关紧要,您使用了*n
)。*args
的目的是创建一个元组,其中包含传递给函数的所有非关键字参数
创建一个元素元组时,始终使用尾随逗号打印,以将其作为元组进行区分。在下面两种情况下,您有一个单独的元素args
元组,其中一个4或2元素元组作为其单独的元素
您的句子“字符串添加到参数时,元组后面出现逗号”不正确——您从调用中删除了解包运算符*
,该运算符不再将元组展平为变量参数,因此字符串与此无关。即使将数字作为唯一参数传递,您仍然会得到挂起的逗号:
>>> type(('test'))
<class 'str'>
>>> type(('test', 1))
<class 'tuple'>
func((1,2,3,'hey'))
func(('hey',1))
>>> type(('test'))
<class 'str'>
>>> type(('test', 1))
<class 'tuple'>
>>> 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,)