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

如何用Python编写代码找出总金额最高的月份?

问题与解决方案

问题背景

给定交易数据列表:

lst = [
    {'account': 'x*', 'amount': 300, 'day': 3, 'month': 'June'},
    {'account': 'y*', 'amount': 550, 'day': 9, 'month': 'May'},
    {'account': 'z*', 'amount': -200, 'day': 21, 'month': 'June'},
    {'account': 'g', 'amount': 80, 'day': 10, 'month': 'May'},
    {'account': 'x*', 'amount': 30, 'day': 16, 'month': 'August'},
    {'account': 'x*', 'amount': 100, 'day': 5, 'month': 'June'},
]

需找出年度内总amount最高的月份,已知结果为June。原尝试代码存在语法错误,且未实现自动遍历找最大值的逻辑。

原代码错误点

  • lambda参数名错误:第一个参数定义为my_dict,但实际传入的是列表,应改为my_list
  • 计算total_August时语法错误:多了一个右括号,正确写法为get_sum(my_list,'August')
  • 仅手动计算个别月份,未通过循环自动筛选出总金额最高的月份

正确实现方案

方案一:修复lambda后通过循环遍历所有月份

先修正lambda函数,再遍历所有唯一月份计算总和,对比找出最大值:

# 修正lambda函数,参数名改为列表对应的my_list
get_sum = lambda my_list, month: sum(d['amount'] for d in my_list if d['month'] == month)

# 获取所有不重复的月份
unique_months = {d['month'] for d in lst}

max_total = -float('inf')
max_month = None

# 循环计算每个月的总金额,记录最大值
for month in unique_months:
    current_total = get_sum(lst, month)
    if current_total > max_total:
        max_total = current_total
        max_month = month

print(f"总金额最高的月份是{max_month},总金额为{max_total}")

方案二:用字典统计月度总金额(更高效)

仅遍历一次原始列表,用字典累加每个月的金额,再找出最大值:

month_totals = {}

# 遍历交易数据,累加每个月的金额
for transaction in lst:
    month = transaction['month']
    amount = transaction['amount']
    month_totals[month] = month_totals.get(month, 0) + amount

# 找出总金额最高的月份
max_month = max(month_totals, key=lambda k: month_totals[k])
max_total = month_totals[max_month]

print(f"总金额最高的月份是{max_month},总金额为{max_total}")

方案二更高效,因为仅需遍历一次原始数据,而方案一需要针对每个月份重新遍历列表计算总和。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:31:11