python - (PYTHON)如何完全添加列表中元素的每第 N 项以生成新列表?

标签 python python-3.x list

假设我们有以下列表

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

现在我想将每 3 个数字相加以提供 6 个列表的长度,

[6, 15, 24, 33, 42, 51]

我想在 python 中做这个....请帮忙! (我的问题措辞奇怪吗?)

到现在我都试过了

z = np.zeros(6)
p = 0
cc = 0
for i in range(len(that_list)):
    p += that_list[i]
    cc += 1
    if cc == 3:
       t = int((i+1)/3)
       z[t] = p
       cc = 0
       p = 0

它没有用......

最佳答案

考虑使用 list comprehension :

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

或者 numpy:

>>> import numpy as np
>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
>>> np.add.reduceat(nums, np.arange(0, len(nums), 3))
>>> array([ 6, 15, 24, 33, 42, 51])

如果出于某种原因需要使用手动循环:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
result = []
group_size, group_sum, group_length = 3, 0, 0
for num in nums:
    group_sum += num
    group_length += 1
    if group_length == group_size:
        result.append(group_sum)
        group_sum, group_length = 0, 0
print(result)  # [6, 15, 24, 33, 42, 51]

关于python - (PYTHON)如何完全添加列表中元素的每第 N 项以生成新列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74259924/

相关文章:

Python:将多个列表连接成一个句子

python - 如何让 python 信任我服务器的 TLS 自签名证书 : ssl. SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败

Python Socket 下载/上传图像文件缺少二进制文件

python - 使用 if else 语句求三角形的面积

python - 在 Python 中使用属性时 Class.foo 和 instance.foo 的不同行为

Python: "IN"(用于列表)如何工作?

javascript - 使用 flask 和 ajax 的跨源问题

python 3 : select() behaves weird with UNIX FIFO

python - 使用 Python 3 从 PDF 解析中提取标题和子标题

python - 创建两个 numpy.ndarray 的字典?