Returning tuple with a single item from a function

瘦欲@ 提交于 2019-12-17 09:56:33

问题


Just came across this little bit of weirdness in Python and thought I'd document it write it as a question here in case anyone else is trying to find an answer with the same fruitless search terms I was

Looks like tuple unpacking makes it so you can't return a tuple of length 1 if you're expecting to iterate over the return value. Although it seems that looks are deceiving. See the answers.

>>> 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
>>>

回答1:


You need to explicitly make it a tuple (see the official tutorial):

def returns_tuple_of_one(a):
    return (a, )



回答2:


This is not a bug, a one-tuple is constructed by val, or (val,). It is the comma and not the parentheses that define the tuple in python syntax.

Your function is actually returning a itself, which is of course not iterable.

To quote sequence and tuple docs:

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.




回答3:


(a) is not a single element tuple, it's just a parenthesized expression. Use (a,).




回答4:


Instead of that ugly comma, you can use the tuple() built-in method.

def returns_tuple_of_one(a):
    return tuple(a)


来源:https://stackoverflow.com/questions/6682093/returning-tuple-with-a-single-item-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!