【问题标题】:Issue with for-loop running through JSON通过 JSON 运行的 for 循环问题
【发布时间】:2019-10-29 08:36:54
【问题描述】:

我似乎无法让 Python 通过 for 循环运行它来从 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:\Python\F1App\f1.py", line 58, in <module>
    getUserInput(input('Please enter your selection: '))
  File "D:\Python\F1App\f1.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: '))

【问题讨论】:

  • 请提供错误的完整回溯,而不仅仅是最后一行。

标签: python json string dictionary for-loop


【解决方案1】:

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

print(i["Driver"]["familyName"])

【讨论】:

    【解决方案2】:

    您需要像这样使用变量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 循环已经在遍历列表。

    【讨论】:

      【解决方案3】:

      你已经在第一行显示了

      (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"])
      

      【讨论】:

        猜你喜欢
        • 2011-08-07
        • 1970-01-01
        • 2011-11-14
        • 1970-01-01
        • 2020-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-12
        相关资源
        最近更新 更多