我正在尝试写一个软件,总结从第三方文本文件的要点。文本文件如下所示:
essi 5
pietari 9
essi 2
pietari 10
pietari 7
aps 25
essi 1main函数的作用是将每个球员得分的总和返回到一个列表中,球员按字母顺序排列。我已经做了所有的事情,除了能够计算数字的和之外,它给了我文本文件中essi和pietari的最后一个数字。下面是我的代码:
def main():
filename = input("Enter the name of the score file: ")
read_file = open(filename, mode="r")
score = {}
for line in read_file:
line = line.rstrip()
name, points = line.split(" ")
score[name] = points
print("Contestant score:")
for key in sorted(score):
print(key,score[key])
if __name__ == "__main__":
main()它给出了这个:
Enter the name of the score file: game.txt
Contestant score:
aps 25
essi 1
pietari 7
Process finished with exit code 0所以基本上我需要的是结果是:
Enter the name of the score file: game.txt
Contestant score:
aps 25
essi 8
pietari 26
Process finished with exit code 0发布于 2021-03-14 00:03:50
在您的代码中,您并没有将计数添加到您的“分数”字典中,而只是用文件中的最后一个值重写了分数。
score = {}
with open('your_file.txt', 'r') as f_in:
for line in map(str.strip, f_in):
if not line:
continue
name, cnt = line.split()
if name not in score:
score[name] = int(cnt)
else:
score[name] += int(cnt)
for name in sorted(score):
print(name, score[name])打印:
aps 25
essi 8
pietari 26发布于 2021-03-14 00:04:51
尝试使用以下命令定义您的字典:
from collections import defaultdict
score = defaultdict(int) # instead of "score = {}"然后将更新更改为
score[name] += int(points)发布于 2021-03-14 00:05:44
您可以在collections中使用Counter来简化这一过程。
记住,您还需要将字符串转换为整数:int(points)
from collections import Counter
scores = Counter()
# ...
for line in read_file:
line = line.rstrip()
name, points = line.split(" ")
scores[name] += int(points)
for name, points in scores.items():
print(name, points)https://stackoverflow.com/questions/66615519
复制相似问题