如何对相同键的值求和

How to sum values of an identical key

我需要 Python 来阅读一个 .txt 文件并总结每个学生当年上学的时间。当同一个学生在文件中有多行时,我需要帮助了解如何执行此操作。 .txt 文件看起来像这样:

约翰0550
约翰0550
莎莉1007

我在 Python 中寻找的最终结果是打印出如下列表:

约翰参加了 1100 小时
Sally 已参加 1007 小时

我知道我不能依赖 dict() 因为它不能容纳相同的键。那么最好的方法是什么?

假设您已经有一个名为 split_line 的函数,该函数 returns 每个学生的姓名/上课时间对。你的算法看起来像:

hours_attented_per_student = {}  # Create an empty dict

with open("my_file.txt", "r") as file:
    for line in file.readlines():
        name, hour = split_line(line)

        # Check whether you have already counted some hours for this student
        if name not in hours_attented_per_student.keys():
             # Student was not encountered yet, set its hours to 0
             hours_attented_per_student[name] = 0

        # Now that student name is in dict, increase the amount of hours attented for the student
        hours_attented_per_student[name] += hours

defaultdict 在这里可能会有帮助:

import re
from collections import defaultdict
from io import StringIO

# Simulate File
with StringIO('''John0550
John0550
Sally1007''') as f:
    # Create defaultdict initialized at 0
    d = defaultdict(lambda: 0)
    # For each line in the file
    for line in f.readlines():
        # Split Name from Value
        name, value = re.split(r'(^[^\d]+)', line)[1:]
        # Sum Value into dict
        d[name] += int(value)

# For Display
print(dict(d))

输出:

{'John': 1100, 'Sally': 1007}

假设值已经被拆分和解析:

from collections import defaultdict

entries = [('John', 550), ('John', 550), ('Sally', 1007)]

d = defaultdict(int)
for name, value in entries:
    # Sum Value into dict
    d[name] += int(value)

# For Display
print(dict(d))