发布网友 发布时间:2023-01-11 20:46
共1个回答
热心网友 时间:2023-10-29 15:36
#coding=utf-8
file_path = '/file.txt' # 文件路径
mapping = {} # 聚合映射表
with open(file_path, 'r', encoding='utf-8') as local_file:
for line in local_file: # 遍历每行
key, value = line.strip().split(' ') # 获取每行的两个字段
if key not in mapping:
mapping[key] = 0 # 如果不在映射中就初始化为0
mapping[key] += int(value) # 加和
results = sorted(list(mapping.items()), lambda x:x[0], reverse=False) # 按key值排序并转为列表
for result in results:
print(result[0], result[1]) # 打印