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

如何用Python合并三个二元元组列表并按首元素去重求和?

问题描述

现有三个二元元组列表:

a1 = [(47, 100)]
a2 = [(47, 100), (0, 86), (4, 86)]
a3 = [(47, 100), (39, 90)]

需要将它们合并,按元组的第一个元素去重,对应第二个元素求和,最终得到结果:

a = [(47, 300), (0, 86), (4, 86), (39, 90)]

请问如何用Python实现该需求?


方法一:普通字典累加

通过遍历所有列表的元组,用字典键存储元组第一个元素,值累加对应第二个元素,最后转换为目标格式:

a1 = [(47, 100)]
a2 = [(47, 100), (0, 86), (4, 86)]
a3 = [(47, 100), (39, 90)]

result_dict = {}
# 遍历所有列表
for lst in [a1, a2, a3]:
    for key, value in lst:
        if key in result_dict:
            result_dict[key] += value
        else:
            result_dict[key] = value
# 转换为目标列表格式
a = list(result_dict.items())
print(a)  # 输出: [(47, 300), (0, 86), (4, 86), (39, 90)]

方法二:用collections.defaultdict简化逻辑

defaultdict可自动处理键不存在的情况,省去判断步骤:

from collections import defaultdict

a1 = [(47, 100)]
a2 = [(47, 100), (0, 86), (4, 86)]
a3 = [(47, 100), (39, 90)]

result_dict = defaultdict(int)
for lst in [a1, a2, a3]:
    for key, value in lst:
        result_dict[key] += value

a = list(result_dict.items())
print(a)

方法三:Python 3.10+ 结合collections.Counter

利用Counter的累加特性,配合生成器遍历所有元组:

from collections import Counter

a1 = [(47, 100)]
a2 = [(47, 100), (0, 86), (4, 86)]
a3 = [(47, 100), (39, 90)]

counter = Counter()
# 生成器表达式遍历所有元组
for key, val in (item for lst in [a1,a2,a3] for item in lst):
    counter[key] += val

a = list(counter.items())
print(a)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:50:33