首页 > 解决方案 > 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"])

标签: pythonloops

解决方案


  1. 您想循环遍历 中的元素jsonResponse["results"],而不是jsonResponse.
  2. 您的循环将提供实际元素,而不是它们的索引。

这让你:

for item in jsonResponse["results"]:
    print(item["name"])

推荐阅读