如何检查列表中是否存在具有特定索引的元素?

2024-04-19 06:08:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我提取从第三方服务器接收的数据:

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

我该如何改变我的状况?你知道吗


Tags: and数据in服务器json元素fordata
1条回答
网友
1楼 · 发布于 2024-04-19 06:08:29

您的result[38]值是None,并且len(result[38])失败,因为None单例没有长度。即使不是None,您的测试也可能失败,因为您需要39个元素才能存在索引38,但您只测试至少有38个元素的情况。如果正好有38个元素,您的len(result) >= 38测试将是真的,但您仍然会得到一个IndexError。你知道吗

使用异常处理,而不是测试每个元素:

data = json.loads(response)
try:
    for item in data['result'][38][2]:
        # ...
except (KeyError, TypeError, IndexError):
    # either no `result` key, no such index, or a value is None
    pass

这比测试所有中间元素要简单得多:

if result and len(result) > 38 and result[38] and len(result[38]) > 2:

相关问题 更多 >