python中带索引的字典问题

2024-03-29 15:03:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我写这个程序是为了得到两个字典,dict1以名字为键,获胜次数为值,dict2以年份为键,获胜次数为值。我的问题是,当我试图将当前年份放入需要dict 1的for循环时,它总是给我和“index error:list index out of range” 问题就在这里,因为它显示“年团队[年]=赢家[年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()

Tags: orandinforindexifbetween次数