刚发现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 >>>
您需要明确地使其成为一个元组(请参阅官方教程):
def returns_tuple_of_one(a): return (a, )