首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从文本文件中求和相同键的值

从文本文件中求和相同键的值
EN

Stack Overflow用户
提问于 2021-03-13 23:54:26
回答 3查看 134关注 0票数 1

我正在尝试写一个软件,总结从第三方文本文件的要点。文本文件如下所示:

代码语言:javascript
复制
essi 5
pietari 9
essi 2
pietari 10
pietari 7
aps 25
essi 1

main函数的作用是将每个球员得分的总和返回到一个列表中,球员按字母顺序排列。我已经做了所有的事情,除了能够计算数字的和之外,它给了我文本文件中essi和pietari的最后一个数字。下面是我的代码:

代码语言:javascript
复制
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()

它给出了这个:

代码语言:javascript
复制
Enter the name of the score file: game.txt
Contestant score:
aps 25
essi 1
pietari 7

Process finished with exit code 0

所以基本上我需要的是结果是:

代码语言:javascript
复制
Enter the name of the score file: game.txt
Contestant score:
aps 25
essi 8
pietari 26

Process finished with exit code 0
EN

回答 3

Stack Overflow用户

发布于 2021-03-14 00:03:50

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

代码语言:javascript
复制
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])

打印:

代码语言:javascript
复制
aps 25
essi 8
pietari 26
票数 1
EN

Stack Overflow用户

发布于 2021-03-14 00:04:51

尝试使用以下命令定义您的字典:

代码语言:javascript
复制
from collections import defaultdict
score = defaultdict(int)   # instead of "score = {}"

然后将更新更改为

代码语言:javascript
复制
score[name] += int(points)
票数 0
EN

Stack Overflow用户

发布于 2021-03-14 00:05:44

您可以在collections中使用Counter来简化这一过程。

记住,您还需要将字符串转换为整数:int(points)

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66615519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档