【问题标题】:IndexError : list index out of range while loopingIndexError:循环时列表索引超出范围
【发布时间】:2020-01-20 13:30:00
【问题描述】:

当使用以下代码段运行该函数时,我得到了

IndexError: 列表索引越界错误

#header value
headers = {
    'Authorization': 'Key '+ api_key,
    'Content-Type': 'application/json'
}

#payload value
payload = {
    "inputs":[
        {
            "data":{
                "image":{
                    "url": image_url
                }
            }
        }
    ]
}

response = requests.post('https://api.clarifai.com/v2/models/bd367be194cf45149e75f01d59f77ba7/outputs', headers=headers, json=payload)
tags=[]
#print(response.json())
for x in response.json()["outputs"][0]["data"]["concepts"]:
    tags.append(x['name'])
return tags

为什么索引超出范围以及如何解决这个问题。 任何帮助将不胜感激!

【问题讨论】:

  • 你确定 response.json()["outputs"] 返回一个非空列表吗?
  • print(response.json())的输出是什么
  • 是的 response.json()["outputs"]... 有效
  • 输出是什么?
  • print(response.json()) 给出 :: status : code :10000 description : OK 并打印整个输出。

标签: python json python-requests index-error


【解决方案1】:

x 是一个列表。将其修改为 x[0]["name"] 就可以了。

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 2022-09-23
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2015-06-26
    相关资源
    最近更新 更多