【发布时间】:2020-10-23 11:38:16
【问题描述】:
我的 for 循环无法正常工作。
我想对相同的键进行分组并对它们的值求和。
例如,将所有yes 值相加并显示在一行中。
game.txt 中的信息如下所示:
yes 5
maybe 9
yes 2
maybe 10
maybe 7
no 25
yes 1
印刷品是这样的;
{'no': '25', 'yes': '1', 'maybe': '10'}
我的代码是这样的;
test_scores = {}
filename = input("Enter the name of the score file: ")
file = open(filename, mode="r")
print("Contestant score: ")
for file_line in sorted(file):
key, value = file_line.split()
if key not in test_scores:
test_scores.update({key: value})
print(test_scores)
那么问题似乎是什么以及如何解决呢?
【问题讨论】:
-
您希望打印出来的效果如何?您使用的是字典,因此每个键只能出现一次。
-
你想对这些值求和吗?
-
对不起,应该更具体。我需要总结每一个是,不是,也许在一起,所以我需要一个打印,可能有 26 no 25 yes 8,按字母顺序,在单独的行中。我对编码很陌生。
标签: python file dictionary for-loop