python - 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()
解决方案
大概您的'worldserieswinners.txt'
文件少于 107 (2010 - 1903) 行,因此索引year-1903
超出范围。
推荐阅读
- c# - 在 WPF 中使用 DataGrid 更新 SQL 数据库
- java - Spring Boot bean 验证
- c++ - C++ MPI 发送真但接收假
- mdx - DAX 中等效的 MDX 链接成员
- java - 使用 javax.xml.validation.Validator 对 XSD 进行 XML 验证:无法解析来自第二个 XSD 的类型
- r - 使用 mutate() 或 for-loop 计算另一列中一列的最高当前值
- r - 使用 R 中的 lapply 函数合并具有相同元素的多个子列表
- node.js - 如何在我的 axios 发布请求中正确添加标头,发布路由在邮递员中有效,但在使用 axios 时无效
- c# - XDocument:如何在嵌套的 xml 中查找属性值
- sql - SQL Server-如何执行与 Excel 索引/匹配相同的功能?