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

Python如何对嵌套列表中同首元素条目求和并去重

实现思路

  • 选择字典作为分组统计的中间容器,以嵌套列表每行的首元素作为唯一键,天然避免重复
  • 遍历原始列表的每一条条目:
    • 先将条目中后两位的字符串格式数值转为整数类型
    • 若当前条目首元素已经在字典中存在,就将两个数值分别累加到字典对应存储的值上
    • 若不存在,就以该首元素为键,两个数值为初始值存入字典
  • 最后将字典的键值对重新组装成和原格式一致的嵌套列表,累加后的数值转回字符串类型即可

代码示例

基础实现(无需引入额外依赖)

original_list = [['AAA', '1000', '100'],
                 ['AAA', '500', '25'],
                 ['AAB', '0', '0']]

group = {}
for item in original_list:
    key = item[0]
    num1 = int(item[1])
    num2 = int(item[2])
    if key in group:
        group[key][0] += num1
        group[key][1] += num2
    else:
        group[key] = [num1, num2]

# 转换为目标格式
result = [[k, str(v[0]), str(v[1])] for k, v in group.items()]
print(result)

运行后输出结果为:[['AAA', '1500', '125'], ['AAB', '0', '0']],完全符合需求。

简化写法(用标准库工具)

如果习惯用Python标准库的工具类,可以用defaultdict省去键存在性的判断逻辑:

from collections import defaultdict

original_list = [['AAA', '1000', '100'],
                 ['AAA', '500', '25'],
                 ['AAB', '0', '0']]

group = defaultdict(lambda: [0, 0])
for item in original_list:
    key = item[0]
    group[key][0] += int(item[1])
    group[key][1] += int(item[2])

result = [[k, str(v[0]), str(v[1])] for k, v in group.items()]
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:09:03