我提取从第三方服务器接收的数据:
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]
)的子元素,但看起来它不起作用,因为我得到以下异常-
if result and len(result)>=38 and len(result[38])>=2:
TypeError: object of type 'NoneType' has no len()
或者
for item in result[38][2]:
TypeError: 'NoneType' object is not iterable
我该如何改变我的状况?你知道吗
您的
result[38]
值是None
,并且len(result[38])
失败,因为None
单例没有长度。即使不是None
,您的测试也可能失败,因为您需要39个元素才能存在索引38,但您只测试至少有38个元素的情况。如果正好有38个元素,您的len(result) >= 38
测试将是真的,但您仍然会得到一个IndexError
。你知道吗使用异常处理,而不是测试每个元素:
这比测试所有中间元素要简单得多:
相关问题 更多 >
编程相关推荐