54 if 'iden-6ren">
gpt4 book ai didi

python - 如果我不尝试迭代,为什么我会得到 "type ' bool' is not iterable"?

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

有高超 python 技能的人可以解释为什么当我只进行一些字典查找和比较时会出现“bool is not iterable”错误吗?

这是堆栈跟踪的最后一行:

---> 54     if 'identifiers' in document and 'doi' in document['identifiers'] and document['identifiers']['doi'] == row['doi']:
55 print 'Found DOI'
56 return True

TypeError: ("argument of type 'bool' is not iterable", u'occurred at index 2914')

最佳做法是使用 try/except 尝试读取我的字典并在键不存在时捕获吗?

最佳答案

当对象不提供 contains() 时,in 会尝试迭代它 ( https://docs.python.org/2/reference/expressions.html#membership-test-details )

>>> print 1 in True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
>>>

问题似乎是 key 确实存在,但类型错误,因此 in 检查在这里没有帮助。一般来说,在python中最好遵循EAFP并处理异常,而不是尝试预先检查所有内容。

关于python - 如果我不尝试迭代,为什么我会得到 "type ' bool' is not iterable"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23524444/

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