为什么在 args 中使用一个参数时函数的结果不同?
Why the result of the function is different when one argument used in args?
当我在 args 中传递 1 个参数时,它在元组中传递 returns/prints 参数和逗号。但为什么不在 2 个或更多参数后添加逗号?
def print_args(*args):
print(args)
#If arguments are more than one or zero:
print_args(1,2,3) #Out: (1,2,3)
print_args(1,2) #Out: (1,2)
print_args() #Out: ()
#If I pass 1 argurment:
print_args(1) #Out: (1,) ?
print_args("a") #Out: ('a',)?
print_args([]) #Out: ([],) ?
#Using return statement instead of print():
def return_args(*args):
return args
return_args(1,2) #Out: (1, 2)
return_args(1) #Out: (1,)
在单个项目周围添加括号与冗余分组相同,并且不会将对象创建为元组。来自 docs:
A special problem is the construction of tuples containing 0 or 1
items: the syntax has some extra quirks to accommodate these. Empty
tuples are constructed by an empty pair of parentheses; a tuple with
one item is constructed by following a value with a comma (it is not
sufficient to enclose a single value in parentheses).
docs 最后评论说这个实现确实“丑陋但有效”。
当我在 args 中传递 1 个参数时,它在元组中传递 returns/prints 参数和逗号。但为什么不在 2 个或更多参数后添加逗号?
def print_args(*args):
print(args)
#If arguments are more than one or zero:
print_args(1,2,3) #Out: (1,2,3)
print_args(1,2) #Out: (1,2)
print_args() #Out: ()
#If I pass 1 argurment:
print_args(1) #Out: (1,) ?
print_args("a") #Out: ('a',)?
print_args([]) #Out: ([],) ?
#Using return statement instead of print():
def return_args(*args):
return args
return_args(1,2) #Out: (1, 2)
return_args(1) #Out: (1,)
在单个项目周围添加括号与冗余分组相同,并且不会将对象创建为元组。来自 docs:
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).
docs 最后评论说这个实现确实“丑陋但有效”。