从函数返回包含单个项目的元组
刚刚在 Python 中遇到了这一点奇怪的地方,我想我应该记录它 在这里将其写为一个问题,以防其他人试图使用与我相同的毫无结果的搜索词找到答案。 was
看起来元组解包使得如果您希望迭代返回值,则无法返回长度为 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
>>>
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
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要显式地将其设为元组(请参阅官方 教程):
You need to explicitly make it a tuple (see the official tutorial):
这不是一个错误,一元组是由
val,
或(val,)
构造的。在 python 语法中定义元组的是逗号而不是括号。您的函数实际上返回
a
本身,这当然是不可迭代的。引用序列和元组文档:
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)
不是单个元素元组,它只是一个带括号的表达式。使用(a,)
。(a)
is not a single element tuple, it's just a parenthesized expression. Use(a,)
.您可以使用
tuple()
内置方法来代替那个丑陋的逗号。Instead of that ugly comma, you can use the
tuple()
built-in method.