python - 为什么在 args 中使用一个参数时函数的结果不同?

标签 python jupyter-notebook args

当我在 args 中传递 1 个参数时,它返回/打印元组中的参数和逗号。但是为什么不在 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最后评论说这个实现确实“丑陋,但有效”。

关于python - 为什么在 args 中使用一个参数时函数的结果不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67188545/

相关文章:

python - IRR 库仅适用于支付期和复利期以年为单位的情况(工程经济)

python - 如何在 Jupyter Notebook 中使用 sklearn tree 和 export_graph_viz 调整树的图像大小

ipython-notebook - 如何使用 Jupyter 笔记本进行彩色打印

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 4 at JT1. main(JT1.java:11)

python - Pandas:创建具有零值的缺失组合行

python - 为什么将 hg.Vec3() 向量传递给由它修改的 Python 函数?

python - wiki/docbook/latex文档模板系统

python - bqplot:性能问题

python - 在 Python 命令行参数中拆分长参数

python - args 在 python 中被映射到 kwargs