【发布时间】:2015-03-14 21:49:48
【问题描述】:
我提取从第 3 方服务器接收到的数据:
data = json.loads(response)
if data:
result = data.get('result')
if result and len(result)>=38 and len(result[38])>=2:
for item in result[38][2]:
...
条件的想法是检查列表是否包含索引为 38 (result[38]) 的元素和索引为 2 (result[38][2]) 的子元素,但看起来它不起作用,因为我得到以下异常 -
如果结果和 len(result)>=38 和 len(result[38])>=2:
TypeError: 'NoneType' 类型的对象没有 len()
或
对于结果中的项目[38][2]:
TypeError: 'NoneType' 对象不可迭代
我应该如何修改我的状况?
【问题讨论】:
-
捕获
IndexError异常可能是解决方案之一。 -
result[38]的值为 None。 -
此外,您可以检查
result[38]的类型list。像if result and len(result)>=38 and type(result[38]) == list and len(result[38])>=2:一样,但我建议您使用try/catch块捕获可能的异常,例如IndexError和TypeError。
标签: python