gpt4 book ai didi

python - 期待 ValueError : too many values to unpack but getting TypeError: 'bool' object is not iterable

转载 作者:行者123 更新时间:2023-11-28 17:04:33 25 4
gpt4 key购买 nike

Python 2.7.10(默认,2015 年 9 月 17 日,03:50:35)[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] 在 linux2 上

>>> def f():
... return True
...
>>>
>>> a,b = f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not iterable

对比

>>> def f():
... return 'True'
...
>>>
>>> a,b = f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

为什么不同?

最佳答案

因为 bool 对象是不可迭代的,即使 bool 对象是可迭代的,它也会做和第二个例子一样的事情。

例子:

for i in True:
print(i)

引发和错误:

Traceback (most recent call last):
File "C:\Users\rep\Desktop\code\so.py", line 3517, in <module>
for i in True:
TypeError: 'bool' object is not iterable

但是:

for i in 'True':
print(i)

返回:

T
r
u
e

还有:

要解决它们,请执行以下操作:

a,b = f(),f()

正如@ggorlen 所说,做:

def f(): return "Tr"

然后:

a, b = f()

关于python - 期待 ValueError : too many values to unpack but getting TypeError: 'bool' object is not iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51904836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com