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

Python如何将列表中每N个连续元素求和生成新列表

连续3元素求和的Python实现修复与优化

原代码问题分析

你的代码核心逻辑没问题,但索引计算错误导致无法正常运行:
当处理到第3个元素(索引i=2)时,(i+1)/3 = 1,会把第一个求和结果放到z[1],而正确位置应该是z[0];后续所有结果都会偏移一位,最后一次循环时i=17,(17+1)/3=6,超出了z的最大索引5,直接触发索引越界错误。

修复后的代码

调整索引计算逻辑,用更直观的分组计数器来记录位置:

import numpy as np

that_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
z = np.zeros(6)
p = 0
cc = 0
group_idx = 0  # 记录当前是第几个分组
for i in range(len(that_list)):
    p += that_list[i]
    cc += 1
    if cc == 3:
        z[group_idx] = p
        cc = 0
        p = 0
        group_idx += 1

print(z.tolist())  # 输出:[6.0, 15.0, 24.0, 33.0, 42.0, 51.0]

更简洁的实现方式

1. 纯Python列表推导式(无需依赖numpy)

利用切片每次取3个连续元素,直接求和:

that_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
result = [sum(that_list[i:i+3]) for i in range(0, len(that_list), 3)]
print(result)  # 输出:[6, 15, 24, 33, 42, 51]

2. numpy高效实现(适合大数据量)

通过reshape将数组分组,再按行求和:

import numpy as np

that_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
arr = np.array(that_list)
result = arr.reshape(-1, 3).sum(axis=1).tolist()
print(result)  # 输出:[6, 15, 24, 33, 42, 51]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:25:26