【问题标题】:Method returns TypeError: list indices must be integers or slices, not str方法返回 TypeError:列表索引必须是整数或切片,而不是 str
【发布时间】:2020-08-06 15:41:18
【问题描述】:

我正在使用 openweathermap 来获取返回 JSON 对象的天气数据,如下所示:

blank = {
    "coord": {"lon": -92.11, "lat": 46.78},
    "weather": [
        {"id": 800, "main": "Unknown", "description": "Unknown", "icon": "01d"}
    ],
    "base": "stations",
    "main": {
        "temp": 0,
        "feels_like": 0,
        "temp_min": 0,
        "temp_max": 0,
        "pressure": 0,
        "humidity": 0,
    },
    "visibility": 0,
    "wind": {"speed": 0, "deg": 0},
    "clouds": {"all": 1},
    "dt": 0,
    "sys": {"type": 1, "id": 3903, "country": "US", "sunrise": 0, "sunset": 0},
    "timezone": 0,
    "id": 0,
    "name": "Unknown",
    "cod": 0,
}

我在返回 ["weather"]["description"] 上的字符串时遇到问题,这将引发类型错误 TypeError: list indices must be integers or slices, not str

方法:

class OpenWeather:
    def descrip(self):
        return self.data["weather"]["description"]

有人有什么建议吗?

【问题讨论】:

  • self.data["weather"]是什么东西?
  • 现在,“天气”是一个包含一个元素的列表,即字典。我建议删除方括号,从而使“天气”本身成为字典,除非您需要保持这种方式,在这种情况下,Jan 的答案有效。

标签: python json openweathermap


【解决方案1】:

应该是

class OpenWeather:
    def descrip(self):
        return self.data["weather"][0]["description"]
        #                          ^^^

或者某种列表理解,因为weather 是一个列表(可能是一个字典列表,但您的示例只包含一个字典)。

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2018-10-13
    相关资源
    最近更新 更多