我目前正在组建一个计划,该计划将获得美国世界系列赛(棒球队)的每一位获胜者,并与他们一起形成2个词典。我选择的代码是遵循目标的参数,(没有关键; 1904年或2015年的价值,因为没有世界系列)我认为我的问题是缺乏对词典的理解,如果你认为我误用了一个函数或值我很感激帮助。随意惩罚,我希望学习。
def main():
start=1903
input_file=open('WorldSeriesResults.txt','r')
winners=input_file.readlines()
year_dict={}
count_dict={}
好的所以我已经阅读了文件并创建了词典,年份为year_dict:获胜者和获胜者count_dict:胜利计数。
for i in range(len(winners)):
team=winners[i].rstrip("\n")
year=start+i
if year>= 1904:
year += 1
if year>= 1994:
year += 1
year_dict[str(year)] = team
if team in count_dict:
count_dict[team] += 1
else:
count_dict[team]=1
好的,所以我创建了一个范围循环来方便字典的处理。文件(现在列表)逐行剥离并连接到相应的年份(1-A,2-B,3-C等),同时根据需要跳过1904和1994。然后使用搜索search
函数计算每个团队在列表中出现的次数,然后分别将该数字添加到count_dict。在这一点上,我认为我已经完成了每个词典的完美,我在这两个词上都进行了print
,看起来我是对的。
while True:
year=int(input("Enter a year between 1903-215 excluding 1904 and 1994: "))#prompt user
if year == 1904:
print("There was no winner that year")
elif year == 1994:
print("There was no winner that year")
elif year<1903 or year>2015:
print("The winner of that year in unkown")
else:
winner=year_dict[year]
wins=count_dict[winner]
print("The team that won the world series in", year, "was the", winner
print("The", winner, "won the world series",wins, "times.")
break
这里我提示用户输入。我希望这是下一个关键。用户提供输入,如果有效,它应该是用于获得答案的密钥,但密钥似乎不起作用。
答案 0 :(得分:1)
替换
winner=year_dict[year]
通过
winner=year_dict[str(year)]
因为您使用字符串来填充字典。
答案 1 :(得分:0)
你的问题很简单,你的两个词典keys
和year_dict
都很简单。 count_dict
格式为string
,因此当您在dict
循环中查询while
时,需要将其转换回string
,如下所示:
while True:
year=int(input("Enter a year between 1903-215 excluding 1904 and 1994: "))#prompt user
if year == 1904:
print("There was no winner that year")
elif year == 1994:
print("There was no winner that year")
elif year<1903 or year>2015:
print("The winner of that year in unkown")
else:
winner=year_dict[str(year)]
wins=count_dict[str(winner)]
print("The team that won the world series in", year, "was the", winner
print("The", winner, "won the world series",wins, "times.")
break