【发布时间】:2011-07-13 16:14:04
【问题描述】:
刚刚在 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
>>>
【问题讨论】:
-
感谢大家的解释。这很有意义。谁能解释投票否决?您可以看到我最初的想法是如何从函数返回值而不是元组本身的实际构造导致我进行了一堆徒劳的搜索和实验,因此提出来似乎很合适。 (虽然显然我选择的词可能会更好,请参阅上面的编辑。)
标签: python function return-value iterable-unpacking