You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

处理API数据时遇TypeError:列表索引需为整数或切片而非字符串

问题分析与解决

错误原因

从你的程序输出能明确看到,response["response"]对应的是一个列表(被[]包裹,内部包含多个球队字典),而非单个字典。你直接用字符串"team"作为索引去访问列表,自然会触发TypeError: list indices must be integers or slices, not str——因为列表仅支持整数或切片作为索引。

修复方案

1. 获取单支球队数据(以第一支为例)

给列表添加整数索引定位到具体球队字典后,再提取目标数据:

import requests

url = "https://api-football-v1.p.rapidapi.com/v3/teams"
querystring = {"league":"39","season":"2022"}
headers = {
    "X-RapidAPI-Key": "1b6ce2494dmshf74f9c461b4cdbbp1d3b11jsndd6ab0d8575c",
    "X-RapidAPI-Host": "api-football-v1.p.rapidapi.com"
}

response = requests.get(url, headers=headers, params=querystring).json()

# 提取列表中第一支球队的信息
first_team = response["response"][0]["team"]
print(f"{first_team['id']} {first_team['name']}")

2. 遍历所有球队数据

如果需要处理返回的全部20支球队,用循环遍历列表即可:

import requests

url = "https://api-football-v1.p.rapidapi.com/v3/teams"
querystring = {"league":"39","season":"2022"}
headers = {
    "X-RapidAPI-Key": "1b6ce2494dmshf74f9c461b4cdbbp1d3b11jsndd6ab0d8575c",
    "X-RapidAPI-Host": "api-football-v1.p.rapidapi.com"
}

response = requests.get(url, headers=headers, params=querystring).json()

# 遍历所有球队并打印信息
for item in response["response"]:
    team = item["team"]
    print(f"{team['id']} {team['name']}")

额外提示

  • 调用GET请求时,直接用requests.get()比requests.request("GET", ...)更简洁。
  • 注意保护你的X-RapidAPI-Key,不要随意公开,避免密钥被滥用。

内容的提问来源于stack exchange,提问作者formlessform

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:53:25