python函数返回元组平均数_关于python:使用函数中的单个项返回元组

刚刚在python中发现了这一点奇怪之处,我想我会在这里把它作为一个问题写下来,以防其他人试图用我以前的搜索词来寻找答案。

看起来tuple解包使它成为这样,所以如果您希望遍历返回值,就不能返回长度为1的tuple。虽然外表看起来很骗人。看看答案。

>>> def returns_list_of_one(a):

...     return [a]

...

>>> def returns_tuple_of_one(a):

...     return (a)

...

>>> def returns_tuple_of_two(a):

...     return (a, a)

...

>>> for n in returns_list_of_one(10):

...    print n

...

10

>>> for n in returns_tuple_of_two(10):

...     print n

...

10

10

>>> for n in returns_tuple_of_one(10):

...     print n

...

Traceback (most recent call last):

File"", line 1, in

TypeError: 'int' object is not iterable

>>>

感谢大家的解释。这完全有道理。有人能解释投票被否决的原因吗?你可以看到我最初的想法,它与从函数返回值有关,而不是与元组本身的实际构造有关,这导致我进行了一系列毫无结果的搜索和试验,所以它似乎是合适的提出。(虽然很明显,我选择的单词可能会更好,请参阅上面的编辑。)

您需要显式地将其设置为元组(请参见官方教程):

def returns_tuple_of_one(a):

return (a, )

对。实际上是逗号,而不是括号组成了一个元组。

是的。它也有很好的记录。

这不是bug,一个tuple由val,或(val,)构造。用Python语法定义元组的是逗号而不是括号。

你的函数实际上是返回a本身,这当然是不可测的。

引用序列和元组文档:

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). Ugly, but

effective.

(a)不是单元素元组,它只是一个带圆括号的表达式。使用(a,)。

您可以使用tuple()内置方法,而不是难看的逗号。

def returns_tuple_of_one(a):

return tuple(a)

我同意这是更漂亮的,但不幸的是,tuple(10)给出了相同的TypeError: 'int' object is not iterable。

同样不幸的是,tuple('HELLO')产生('H', 'E', 'L', 'L', 'O'),我不希望从returns_tuple_of_one('HELLO')得到。

tuple([a])更丑,但会起作用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值