我目前正在形成一项计划,要求美国世界大赛(棒球)的每一位获胜者与他们形成2个字典。我选择的代码是遵循目标的参数(没有关键; 1904年或2015年的价值,因为没有世界系列)我认为我的问题是缺乏对字典的理解,如果你认为我滥用功能或价值Id感谢帮助。随意惩罚,我想学习。词典中的键
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
我在这里提示用户输入。我希望这是下一个关键。用户给出了一个输入,如果它的有效,它应该是用于得到答案的关键,但该关键似乎不起作用。