汇总文本文件中相同键的值

2024-06-06 16:58:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图写一个软件,总结从第三方文本文件的点。这是文本文件的外观:

essi 5
pietari 9
essi 2
pietari 10
pietari 7
aps 25
essi 1

主要功能是将每个玩家的得分总和返回到一个列表中,玩家按字母顺序排列。我已经做了所有的事情,除了能够计算数字的总和,它给了我文本文件中埃西和皮埃塔里的最后一个数字。这是我的密码:

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

Tags: ofthekeynamemainline玩家file
3条回答

请尝试使用以下内容定义词典:

from collections import defaultdict
score = defaultdict(int)   # instead of "score = {}"

然后将更新更改为

score[name] += int(points)

您可以使用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)

在代码中,您并没有将计数添加到的“score”字典中,只使用文件中的最后一个值重写分数

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

相关问题 更多 >