python - TypeError:列表索引必须是整数或切片,而不是python循环中的str
问题描述
我一直在寻找其他答案,例如(this)并且没有任何运气。我正在编写一个脚本来从 API 中提取数据。
我想遍历结果字典并提取每个结果的详细信息,例如名称、人口等。使用 json.dumps 的结果响应示例如下:
{
"count": 61,
"next": "https://swapi.co/api/planets/?page=2",
"previous": null,
"results": [
{
"climate": "temperate",
"created": "2014-12-10T11:35:48.479000Z",
"diameter": "12500",
"edited": "2014-12-20T20:58:18.420000Z",
"films": [
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/1/"
],
"gravity": "1 standard",
"name": "Alderaan",
"orbital_period": "364",
"population": "2000000000",
"residents": [
"https://swapi.co/api/people/5/",
"https://swapi.co/api/people/68/",
"https://swapi.co/api/people/81/"
],
"rotation_period": "24",
"surface_water": "40",
"terrain": "grasslands, mountains",
"url": "https://swapi.co/api/planets/2/"
},
{
"climate": "temperate, tropical",
"created": "2014-12-10T11:37:19.144000Z",
"diameter": "10200",
"edited": "2014-12-20T20:58:18.421000Z",
"films": [
"https://swapi.co/api/films/1/"
],
"gravity": "1 standard",
"name": "Yavin IV",
"orbital_period": "4818",
"population": "1000",
"residents": [],
"rotation_period": "24",
"surface_water": "8",
"terrain": "jungle, rainforests",
"url": "https://swapi.co/api/planets/3/"
},
{
"climate": "frozen",
"created": "2014-12-10T11:39:13.934000Z",
"diameter": "7200",
"edited": "2014-12-20T20:58:18.423000Z",
"films": [
"https://swapi.co/api/films/2/"
],
"gravity": "1.1 standard",
"name": "Hoth",
"orbital_period": "549",
"population": "unknown",
"residents": [],
"rotation_period": "23",
"surface_water": "100",
"terrain": "tundra, ice caves, mountain ranges",
"url": "https://swapi.co/api/planets/4/"
},
Python新手,所以如果有更好的方法可以做到这一点,我愿意接受建议!
在我的测试代码中,我有这个:
print(jsonResponse["results"][1]["name"])
我可以手动将 1 更改为其他数字并获取正确的名称以打印出来。
如果我使用它,我会收到“列表索引必须是整数或切片,而不是 str”消息
for i in jsonResponse:
print(jsonResponse["results"][i]["name"])
解决方案
- 您想循环遍历 中的元素
jsonResponse["results"]
,而不是jsonResponse
. - 您的循环将提供实际元素,而不是它们的索引。
这让你:
for item in jsonResponse["results"]:
print(item["name"])
推荐阅读
- jquery - 使用 jquery 单击更新按钮时未显示引导模式
- python - 在python中只比较多个列表一次
- c# - 将excel工作表复制到不同的工作簿
- angularjs - 每次使用不同的过滤器进行排序时,如何在 JS 的表格中跨页面维护我的索引号?
- ktor - 带有 spring 配置服务器的 Ktor 应用程序
- c# - 任何人都可以将此 linq 代码转换为 SQL 查询(因为我不明白它在做什么)?
- c# - c# Task.WhenAll 在等待完成时阻塞
- java - 滚动时recyclerview中的位置发生变化
- python - 使用 ARIMA 模型进行时间序列分析
- reactjs - React Semantic-ui如何处理带有附加参数的下拉onclick