我正在编写程序,以获取两个字典,dict1以名称为键,获胜次数为值,dict 2以年为键,获胜次数为值。我的问题是,当我尝试在需要dict 1的for循环中获取当前年份时,它总是给我和“索引错误:列表索引超出范围” 问题就在这里,因为它显示“ year_team [year] = winners [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()
答案 0 :(得分:0)
大概您的'worldserieswinners.txt'
文件少于107(2010 − 1903)行,因此索引year-1903
超出范围。