如何在Python中合并列表元组的同名元素并累加对应数值?
解决方法
这里有几种简洁的方式实现同名数据的合并累加:
方法一:基础字典遍历
这是最直观的实现方式,用字典记录每个名字的累计统计值:
# 原始数据 baseball_data = [ ("John Doe", 2, 3), ("Sponge Bob", 4, 5), ("John Doe", 1, 5) ] # 初始化字典存储累计结果 total_stats = {} for name, hits, runs in baseball_data: if name in total_stats: # 累加已有数据 total_stats[name] = (total_stats[name][0] + hits, total_stats[name][1] + runs) else: # 首次出现,初始化数据 total_stats[name] = (hits, runs) # 转换回元组列表格式 result = [(name, *values) for name, values in total_stats.items()] print(result) # 输出:[('John Doe', 3, 8), ('Sponge Bob', 4, 5)]
方法二:用collections.defaultdict简化代码
defaultdict可以自动处理键不存在的情况,省去判断逻辑:
from collections import defaultdict baseball_data = [ ("John Doe", 2, 3), ("Sponge Bob", 4, 5), ("John Doe", 1, 5) ] # 默认值设为(0, 0),避免键不存在的报错 total_stats = defaultdict(lambda: (0, 0)) for name, hits, runs in baseball_data: current_hits, current_runs = total_stats[name] total_stats[name] = (current_hits + hits, current_runs + runs) result = [(name, *values) for name, values in total_stats.items()] print(result) # 输出:[('John Doe', 3, 8), ('Sponge Bob', 4, 5)]
方法三:使用itertools.groupby(需先排序)
如果允许先对数据按名字排序,groupby可以快速分组统计:
from itertools import groupby baseball_data = [ ("John Doe", 2, 3), ("Sponge Bob", 4, 5), ("John Doe", 1, 5) ] # 必须先按名字排序,groupby只能分组连续的相同元素 sorted_data = sorted(baseball_data, key=lambda x: x[0]) result = [] for name, group in groupby(sorted_data, key=lambda x: x[0]): # 将分组转为列表,方便多次遍历 group_items = list(group) total_hits = sum(item[1] for item in group_items) total_runs = sum(item[2] for item in group_items) result.append((name, total_hits, total_runs)) print(result) # 输出:[('John Doe', 3, 8), ('Sponge Bob', 4, 5)]
内容的提问来源于stack exchange,提问作者Dylan Eye
相关产品推荐
相关产品推荐

