刚刚在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])更丑,但会起作用。