相关疑难解决方法(0)

使用函数中的单个项返回元组

刚刚在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
>>>
Run Code Online (Sandbox Code Playgroud)

python function return-value iterable-unpacking

16
推荐指数
2
解决办法
1万
查看次数