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

Python中基于反向索引快照的累计总和计算代码优化咨询

Python中基于反向索引快照的累计总和计算代码优化咨询

嘿,看你已经把核心功能跑通了,现在想让代码更优雅简洁对吧?我来给你几个Pythonic的优化思路,既能保持功能不变,又能让代码更易读、扩展性更强~

先明确下你的核心需求:反向遍历json_message['result']里的子列表,累加每个子列表的第二个元素(转成float后四舍五入到两位小数),当遍历到第1、4、7、10、15个元素时(从反向开头数),把当前的累计值存入totals对应的条目里。

方案一:用映射字典替代冗余的elif判断

原来的一堆elif不仅写起来麻烦,以后要新增或修改目标length时还得改循环逻辑。我们可以先把totals转成一个目标索引→对应条目的字典,遍历的时候直接检查当前索引是否在字典里即可:

json_message = {'result':[[12, 234], [53, 45], [3, 425], [74, 12], [3, 678], [2, 42], [12, 234], [1, 66], [6, 85], [5, 73], [12, 84], [6, 24], [98, 23], [34, 4], [82, 253]]}

total = 0
totals = [{'length': 1, 'total': 0}, {'length': 4, 'total': 0}, {'length': 7, 'total': 0}, {'length': 10, 'total': 0}, {'length': 15, 'total': 0}]

# 构建反向索引(从0开始)到totals条目的映射
target_map = {item['length'] - 1: item for item in totals}

for index, item in enumerate(reversed(json_message['result'])):
    total += round(float(item[1]), 2)
    # 匹配到目标索引就更新对应total
    if index in target_map:
        target_map[index]['total'] = total

print(totals)

这个方案的好处是:逻辑清晰,去掉了冗余的分支判断;以后要调整目标length,只需要修改totals列表,不需要改动循环里的代码,扩展性拉满。

方案二:用生成器+直观计数,贴合需求逻辑

如果你更想贴近“每n个元素记录一次”的直观思路,可以先把要累加的数值提取出来(用生成器节省内存),然后从1开始计数,每到目标length就记录累计值:

json_message = {'result':[[12, 234], [53, 45], [3, 425], [74, 12], [3, 678], [2, 42], [12, 234], [1, 66], [6, 85], [5, 73], [12, 84], [6, 24], [98, 23], [34, 4], [82, 253]]}

# 生成反向的待累加数值(提前处理四舍五入)
values = reversed(round(float(sub[1]), 2) for sub in json_message['result'])

totals = [{'length': 1, 'total': 0}, {'length': 4, 'total': 0}, {'length': 7, 'total': 0}, {'length': 10, 'total': 0}, {'length': 15, 'total': 0}]

# 构建目标length到对应条目的映射
length_map = {item['length']: item for item in totals}

current_total = 0
current_count = 0

for val in values:
    current_count += 1
    current_total += val
    # 匹配到目标length就更新对应total
    if current_count in length_map:
        length_map[current_count]['total'] = current_total

print(totals)

这个方案的优势是:计数从1开始,和你定义的length概念完全对应,不需要做length-1的转换,可读性更强;生成器的使用也让代码更简洁高效。

两种方案都能实现你的需求,而且比原来的代码更优雅,你可以根据自己的习惯和后续扩展需求来选择~

备注:内容来源于stack exchange,提问作者led_farmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 15:13:05