通过 JSON 运行的 for 循环出现问题



我似乎无法通过for循环运行Python来打印JSON中的数据。

我想通过 JSON 文件运行一个 for 循环,并让它从列表中的每个项目打印"familyName"键的值。

当我为列表中的一个项目打印"familyName"键的值时。

print((results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Driver"]["familyName"])

..我得到了我正在寻找的结果:

Hamilton

但是,当我尝试使用 for 循环从列表中的每个项目中获取"familyName"时。

for i in (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]):
            print([0]["Driver"]["familyName"])

..它给出一个错误。

Traceback (most recent call last):
  File "D:PythonF1Appf1.py", line 58, in <module>
    getUserInput(input('Please enter your selection: '))
  File "D:PythonF1Appf1.py", line 32, in getUserInput
    print([0]["Driver"]["givenName"])
TypeError: list indices must be integers or slices, not str

这让我感到困惑,因为它在自己打印时有效,但不能作为 for 循环。我假设我使用了不正确的语法。

提前谢谢你。

以下是指向 JSON 文件的链接:http://ergast.com/api/f1/current/driverStandings.json

如果需要,这是我的所有代码:

import json
import requests
r = requests.get('http://ergast.com/api/f1/current/driverStandings.json')
results_information = r.json()
q = requests.get('http://ergast.com/api/f1/current/next.json')
next_circuit = q.json()
s = requests.get('http://ergast.com/api/f1/current/last.json')
last_circuit = s.json()
status = True
def getUserInput(number):
    if number == '1':
        print()
        print("The leader of the driver standings for the current F1 season is:")
        print((results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Driver"]["givenName"]) + " " + (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Driver"]["familyName"]))
    elif number == '2':
        print()
        print("The leader of the constructor standings for the current F1 season is:")
        print(results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Constructors"][0]["name"])
    elif number == '3':
        print()
        print(('The next race of the current season will be the ') + (next_circuit['MRData']['RaceTable']['Races'][0]['raceName']))
    elif number == '4':
        print()
        print(('The previous race of the current season was the ') + (last_circuit['MRData']['RaceTable']['Races'][0]['raceName']))
    elif number == '5':
        print()
        print('Here are the driver standings for the current F1 season:')
        for i in (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]):
            print([0]["Driver"]["familyName"])
    elif number.lower() == 'e':
        print()
        print('Goodbye.')
        print()
        exit()
    else:
        print()
        print('Please enter a valid input.')
        print()
while status == True:
    print('----------------------------')
    print('Welcome to the F1 Python App')
    print('----------------------------')
    print()
    print('------------MENU------------')
    print('----------------------------')
    print('Enter '1' for leader of the driver standings for the current F1 season.')
    print('Enter '2' for leader of the constructor standings for the current F1 season.')
    print('Enter '3' for location of the upcoming race circuit in the current F1 season.')
    print('Enter '4' for location of the previous race circuit in the current F1 season.')
    print('Enter '5' for the driver standings for the current F1 season.')
    print('Enter 'E' to exit the application.')
    print()
    getUserInput(input('Please enter your selection: '))

您应该注意错误消息告诉您的行。我想你的意思是:

print(i["Driver"]["familyName"])
您需要

使用变量i而不是像这样[0]

for i in (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]):
            print(i["Driver"]["familyName"])

原因是results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]的价值在每次迭代时都存储在变量i中。然后,您可以通过i["Driver"]["familyName"] .您不需要[0]因为 for 循环已经在遍历列表。

您在第一行中显示

(results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"][0]["Driver"]["familyName"]

等于字符串

Hamilton

因此,您的错误发生在尝试遍历此字符串而不是包含该字符串的列表时。

所以这就像说

for i in 'Hamilton'

相反,您应该采用其原始列表:

for i in (results_information["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]):
            print([0]["Driver"])

最新更新