首页 > 解决方案 > python中的字典问题,索引错误

问题描述

我正在编写程序来获取两个字典,dict1 以名称作为键,获胜次数作为值,dict 2 以年作为键,获胜次数作为值。我的问题是当我尝试在需要dict 1的for循环中获取当前年份时,它总是给我和“索引错误:列表索引超出范围”,问题就在这里,因为它显示“year_team [year] =获奖者[1903 年]”。

def main():
    dfile=open('worldserieswinners.txt','r')
    winners=dfile.read().splitlines()

    team_wins={}
    year_team={}

    for team in winners:
        if team not in team_wins:
            team_wins[team]=1
        else:
            team_wins[team]+=1

    for year in range(1903, 2010):
        if year != 1904 and year != 1994:
            year_team[year]=winners[year-1903]

    year=int(input('Enter a year between 1903 and 2009 or 0 to quit: '))
    while year!= 0:
        if year == 1904 or year == 1994:
            print('Not played in this year')
        elif 1903>year or year>2009:
            print('Invalid choice')
        else:
            team=year_team[year]
            wins=team_wins[team]
            print('The winning team in',year,'was the',team)
            print('The',team,'won',wins,'times between 1903 and 2009.')
            year= int(input('Enter a year between 1903 and 2009 or 0 to quit: '))

    dfile.close()

main()

标签: python

解决方案


大概您的'worldserieswinners.txt'文件少于 107 (2010 - 1903) 行,因此索引year-1903超出范围。


推荐阅读