Returning tuple with a single item from a function
刚刚在python中发现了这一点奇怪之处,我想我会在这里把它作为一个问题写下来,以防其他人试图用我以前的搜索词来寻找答案。
看起来tuple解包使它成为这样,所以如果您希望遍历返回值,就不能返回长度为1的tuple。虽然外表看起来很骗人。看看答案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | >>> 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 2 | def returns_tuple_of_one(a): return (a, ) |
这不是bug,一个tuple由
你的函数实际上是返回
引用序列和元组文档:
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.
号
您可以使用
1 2 | def returns_tuple_of_one(a): return tuple(a) |
号