小编典典

从函数中返回带有单个项目的元组

python

刚发现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
>>>

阅读 143

收藏
2020-12-20

共1个答案

小编典典

您需要明确地使其成为一个元组(请参阅官方教程):

def returns_tuple_of_one(a):
    return (a, )
2020-12-20