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

Python 3实现:按年份对字典列表指定key(如x2)求小计

按年份对指定字段求小计的几种Python实现方法

Hey there! 作为Python 3初学者,按年份对指定字段求和其实不难,我给你几个从基础到进阶的实用方法,你可以根据自己的情况选择~

首先先明确一下你的数据结构,应该是类似列表套字典的形式吧?比如:

data = [
    {"year": 1999, "month": 1, "yearmonth": 199901, "x1": 10, "x2": 20, "x3": 30},
    {"year": 1999, "month": 3, "yearmonth": 199903, "x1": 10, "x2": 20, "x3": 30},
    {"year": 2000, "month": 4, "yearmonth": 200004, "x1": 10, "x2": 20, "x3": 30},
    {"year": 2000, "month": 9, "yearmonth": 200009, "x1": 10, "x2": 20, "x3": 30},
    {"year": 2000, "month": 10, "yearmonth": 200010, "x1": 10, "x2": 20, "x3": 30}
]

如果你的数据格式和这个差不多,那下面的方法都适用~

方法一:基础循环法(最适合理解逻辑)

这个方法完全用基础语法实现,能帮你清晰理解“按年份累加”的逻辑:

# 指定你要求和的目标字段,比如这里的x2
target_key = "x2"
# 初始化一个空字典,用来存每个年份的小计结果
yearly_totals = {}

# 遍历每一条数据
for item in data:
    # 取出当前数据的年份和目标字段的值
    current_year = item["year"]
    current_value = item[target_key]
    
    # 如果年份已经在结果字典里,就累加;否则初始化这个年份的小计
    if current_year in yearly_totals:
        yearly_totals[current_year] += current_value
    else:
        yearly_totals[current_year] = current_value

print(yearly_totals)
# 输出结果:{1999: 40, 2000: 60}

方法二:用collections.defaultdict(更简洁)

Python的标准库collections里有个defaultdict,可以帮我们省去“判断年份是否存在”的步骤,代码更简洁:

from collections import defaultdict

target_key = "x2"
# 初始化一个默认值为0的字典,这样遇到新年份时会自动初始化为0
yearly_totals = defaultdict(int)

for item in data:
    # 直接按年份累加目标字段的值即可
    yearly_totals[item["year"]] += item[target_key]

# 如果需要转成普通字典(可选)
yearly_totals = dict(yearly_totals)

print(yearly_totals)
# 输出结果和上面一样:{1999: 40, 2000: 60}

方法三:用Pandas库(处理大量数据更高效)

如果你的数据量比较大,或者以后经常要处理这类表格型数据,Pandas会是你的好帮手,它的分组求和功能非常方便:

import pandas as pd

# 把列表字典转换成DataFrame(类似Excel表格的结构)
df = pd.DataFrame(data)

target_key = "x2"
# 按year分组,然后对目标字段求和,最后转成字典
yearly_totals = df.groupby("year")[target_key].sum().to_dict()

print(yearly_totals)
# 输出结果:{1999: 40, 2000: 60}

注意:如果还没安装Pandas,可以用pip install pandas命令安装哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:32:34