【问题标题】:Sum up values of same key from text file从文本文件中总结相同键的值
【发布时间】:2021-06-11 09:25:55
【问题描述】:

我正在尝试编写一个从第三方文本文件中总结积分的软件。这是文本文件的样子:

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

主函数应该将每个玩家得分的总和返回到一个列表中,并且玩家要按字母顺序排列。除了能够计算数字的总和之外,我已经做了所有事情,它给了我文本文件中 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

【问题讨论】:

  • "计算数字的总和" - 您的代码不会尝试对任何内容求和。这段代码的哪一部分应该实现总和?

标签: python file dictionary


【解决方案1】:

在您的代码中,您没有将计数添加到您的 "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

【讨论】:

    【解决方案2】:

    尝试使用以下方式定义您的字典:

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

    然后将更新改为

    score[name] += int(points)
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2017-05-17
        • 2021-04-23
        • 2018-09-03
        • 1970-01-01
        • 1970-01-01
        • 2016-04-15
        • 2020-09-30
        • 2020-05-18
        • 1970-01-01
        相关资源
        最近更新 更多