gpt4 book ai didi

python - python中的字典问题与索引错误

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:14 24 4
gpt4 key购买 nike

我正在编写程序来获取两个字典,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()

最佳答案

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

关于python - python中的字典问题与索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52551459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com