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

Python入门者求教:如何在多列表中对同id对象的count值求和?

嘿,作为Python入门学习者,这个需求其实挺典型的——咱们要把嵌套列表里相同id的count值累加起来对吧?我给你分享几种实用的实现方式,从基础到进阶都有,你可以根据自己的情况选:

方法一:手动用字典统计(适合新手理解)

这是最直观的方式,一步步拆解逻辑,能帮你理清思路:

data = [
    [{'id': 1, 'count': 10}, {'id': 2, 'count': 20}],
    [{'id': 1, 'count': 20}, {'id': 2, 'count': 30}]
]

# 初始化一个空字典,用来存储每个id对应的总count
count_dict = {}

# 逐层遍历嵌套列表里的每个字典
for sublist in data:
    for item in sublist:
        item_id = item['id']
        item_count = item['count']
        
        # 如果当前id已经在字典里,就累加count;否则设置初始值
        if item_id in count_dict:
            count_dict[item_id] += item_count
        else:
            count_dict[item_id] = item_count

# 把字典转换成你需要的列表格式
result = [{'id': key, 'count': value} for key, value in count_dict.items()]
print(result)
# 输出结果:[{'id': 1, 'count': 30}, {'id': 2, 'count': 50}]

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

Python标准库的collections模块里有个defaultdict,能帮我们省去判断key是否存在的步骤,代码更简洁:

from collections import defaultdict

data = [
    [{'id': 1, 'count': 10}, {'id': 2, 'count': 20}],
    [{'id': 1, 'count': 20}, {'id': 2, 'count': 30}]
]

# 初始化一个默认值为0的字典
count_dict = defaultdict(int)

for sublist in data:
    for item in sublist:
        # 直接累加就行,不存在的key会自动设为0再累加
        count_dict[item['id']] += item['count']

# 同样转成目标格式
result = [{'id': key, 'count': value} for key, value in count_dict.items()]
print(result)

方法三:用Pandas处理(适合大量数据)

如果以后你要处理的数据量很大,或者需要更复杂的数据分析,Pandas会是个好帮手:

import pandas as pd

data = [
    [{'id': 1, 'count': 10}, {'id': 2, 'count': 20}],
    [{'id': 1, 'count': 20}, {'id': 2, 'count': 30}]
]

# 先把嵌套列表展平成一维列表
flattened_data = [item for sublist in data for item in sublist]
# 转成Pandas的DataFrame
df = pd.DataFrame(flattened_data)
# 按id分组,对count求和
sum_df = df.groupby('id')['count'].sum().reset_index()
# 转成字典列表格式
result = sum_df.to_dict('records')
print(result)

这几种方法都能实现你的需求,入门阶段先掌握前两种就足够啦,理解字典的用法对Python学习很重要~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:50:11