使用函数中的单个项返回元组

mcs*_*her 16 python function return-value iterable-unpacking

刚刚在Python中遇到了一些奇怪的想法,我想 会把写成一个问题,以防万一其他人试图用同样的徒劳无益的搜索条件找到答案我是

看起来像元组解包使得它如果你期望迭代返回值就不能返回长度为1的元组.虽然看起来看起来很欺骗.看到答案.

>>> 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 "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
Run Code Online (Sandbox Code Playgroud)

mul*_*ces 32

你需要明确地使它成为一个元组(参见官方教程):

def returns_tuple_of_one(a):
    return (a, )
Run Code Online (Sandbox Code Playgroud)

  • 是.它实际上是逗号,而不是括号,它构成了一个元组. (10认同)
  • 是的.它也很好[详细记录](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). (2认同)

she*_*mer 13

这不是一个错误,一个元组是由val,或构造的(val,).它是逗号,而不是用python语法定义元组的括号.

你的函数实际上正在返回a,这当然是不可迭代的.

引用序列和元组文档:

一个特殊的问题是构造包含0或1项的元组:语法有一些额外的怪癖来适应这些.空元组由一对空括号构成; 通过使用逗号跟随值来构造具有一个项目的元组(仅在括号中包含单个值是不够的).丑陋但有效.