从函数返回单个项目的元组 [英] Returning tuple with a single item from a function

查看:99
本文介绍了从函数返回单个项目的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚在Python中遇到了这种奇怪的东西,并且认为我会将它记录下来 在这里写下它是一个问题,以防其他人试图找到一个同样没有结果的答案搜索条件我是



看起来像tuple unpacking使得它不能返回长度为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(最近的最后一次调用):
文件< stdin>,第1行,在< module>
TypeError:'int'对象不可迭代
>>>


解决方案

您需要明确地将其设置为一个元组教程):

  def returns_tuple_of_one(a):
return(a,)


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

解决方案

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

def returns_tuple_of_one(a):
    return (a, )

这篇关于从函数返回单个项目的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆