本文介绍了带有单个参数的 Python 参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用单个参数测试 Python 参数列表时,我发现 print 有一些奇怪的行为.

>>>定义嗨(* x):... 打印(x)...>>>你好()()>>>嗨(1,2)(1, 2)>>>嗨(1)(1,)

谁能向我解释一下 hi(1) 的结果中最后一个逗号的含义(即 (1,))

解决方案

其实这个行为只是有点怪异".:-)

您的参数 x 以星号为前缀,这意味着您传递给函数的所有参数都将汇总"为一个元组,而 x 将成为那个元组.

(1,) 是 Python 编写一个值的元组的方式,与 (1) 形成对比,后者将是数字 1.

这是一个更一般的情况:

def f(x, *y):返回x 是 {},y 是 {}".format(x, y)

以下是一些运行:

>>>f(1)'x 是 1,y 是 ()'>>>f(1, 2)'x 是 1,y 是 (2,)'>>>f(1, 2, 3)'x 是 1,y 是 (2, 3)'>>>f(1, 2, 3, 4)'x 是 1,y 是 (2, 3, 4)'

注意第一个参数如何进入 x 并且所有后续参数都被打包到元组 y 中.您可能只是发现 Python 表示具有 0 或 1 个组件的元组的方式有点奇怪,但是当您意识到 (1) 必须是一个数字,因此必须有某种方式时,这是有道理的表示一个单元素元组.Python 只是使用尾随逗号作为约定,仅此而已.

When testing Python parameter list with a single argument, I found some weird behavior with print.

>>> def hi(*x):
...     print(x)
...
>>> hi()
()
>>> hi(1,2)
(1, 2)
>>> hi(1)
(1,)

Could any one explain to me what the last comma mean in hi(1)'s result (i.e. (1,))

解决方案

Actually the behavior is only a little bit "weird." :-)

Your parameter x is prefixed with a star, which means all the arguments you pass to the function will be "rolled up" into a single tuple, and x will be that tuple.

The value (1,) is the way Python writes a tuple of one value, to contrast it with (1), which would be the number 1.

Here is a more general case:

def f(x, *y):
    return "x is {} and y is {}".format(x, y)

Here are some runs:

>>> f(1)
'x is 1 and y is ()'
>>> f(1, 2)
'x is 1 and y is (2,)'
>>> f(1, 2, 3)
'x is 1 and y is (2, 3)'
>>> f(1, 2, 3, 4)
'x is 1 and y is (2, 3, 4)'

Notice how the first argument goes to x and all subsequent arguments are packed into the tuple y. You might just have found the way Python represents tuples with 0 or 1 components a little weird, but it makes sense when you realize that (1) has to be a number and so there has to be some way to represent a single-element tuple. Python just uses the trailing comma as a convention, that's all.

这篇关于带有单个参数的 Python 参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:10
查看更多