You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并元组首个元素重复项并计算第二个元素平均值

合并元组并计算相同首元素对应值的平均值实现方法

这里提供三种实用的Python实现方式,都能完成将相同首元素的元组合并,并计算对应第二个元素平均值的需求:

方法一:普通字典手动统计

逻辑直白,手动维护每个颜色的数值总和与出现次数,新手也能轻松看懂:

tuple_list = [('Red', 7), ('Red', 2), ('Red', 4), ('Green', 3), ('Red', 11), ('Green', 6), ('Blue', 8)]

color_stats = {}
for color, num in tuple_list:
    if color in color_stats:
        color_stats[color]['sum'] += num
        color_stats[color]['count'] += 1
    else:
        color_stats[color] = {'sum': num, 'count': 1}

result = [(color, stats['sum'] / stats['count']) for color, stats in color_stats.items()]
print(result)
# 输出: [('Red', 6.0), ('Green', 4.5), ('Blue', 8.0)]

方法二:用collections.defaultdict简化代码

借助defaultdict自动为不存在的键创建空列表,省去键存在性判断,代码更简洁:

from collections import defaultdict

tuple_list = [('Red', 7), ('Red', 2), ('Red', 4), ('Green', 3), ('Red', 11), ('Green', 6), ('Blue', 8)]

color_values = defaultdict(list)
for color, num in tuple_list:
    color_values[color].append(num)

result = [(color, sum(values)/len(values)) for color, values in color_values.items()]
print(result)
# 输出: [('Red', 6.0), ('Green', 4.5), ('Blue', 8.0)]

方法三:itertools.groupby分组计算

注意使用前要先按首元素排序,否则不连续的同颜色元组会被分到不同组:

from itertools import groupby

tuple_list = [('Red', 7), ('Red', 2), ('Red', 4), ('Green', 3), ('Red', 11), ('Green', 6), ('Blue', 8)]

sorted_list = sorted(tuple_list, key=lambda x: x[0])
result = []
for color, group in groupby(sorted_list, key=lambda x: x[0]):
    nums = [num for _, num in group]
    avg = sum(nums)/len(nums)
    result.append((color, avg))

print(result)
# 输出: [('Blue', 8.0), ('Green', 4.5), ('Red', 6.0)]

内容的提问来源于stack exchange,提问作者Delta23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:35:09