gpt4 book ai didi

python - TypeError : list indices must be integers or slices, not str when parsing lists

转载 作者:行者123 更新时间:2023-12-03 08:46:54 26 4
gpt4 key购买 nike

这是我的代码:

import requests
import json

res = requests.get("http://transport.opendata.ch/v1/connections?
from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")

parsed_json = res.json()

print(parsed_json['connections']['from']['prognosis'])
"departure"

但是,如果我运行它,则会出现以下错误:
Traceback (most recent call last):
File "/home/pi/Desktop/Matura/v7/v7_test.py", line 10, in <module>
print(parsed_json['connections']['from']['prognosis'])
TypeError: list indices must be integers or slices, not str

我看过其他类似的问题,但没有找到解决方案
我是编码的新手,所以我不知道问题可能在哪里。

最佳答案

首先让我们检查parsed_json的内容。

{'connections': [{'from': {'prognosis': {'departure': '2018-08-04T11:24:00+0200'}}}, {'from': {'prognosis': {'departure': '2018-08-04T11:53:00+0200'}}}, {'from': {'prognosis': {'departure': '2018-08-04T12:22:00+0200'}}}, {'from': {'prognosis': {'departure': None}}}]}

如果看到输出,则 connections的子代不是 str而是 list。您无法使用 str访问列表中的元素,这就是您收到该错误的原因。

所以改变
print(parsed_json['connections']['from']['prognosis'])

print(parsed_json['connections'][0]['from']['prognosis'])
您可以将 0更改为所需元素的 index

关于python - TypeError : list indices must be integers or slices, not str when parsing lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51684239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com