Dan*_*won 2 python list python-3.x
假设我们有以下列表
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
Run Code Online (Sandbox Code Playgroud)
现在我想将每 3 个数字相加以提供 6 个列表的长度,
[6, 15, 24, 33, 42, 51]
Run Code Online (Sandbox Code Playgroud)
我想在 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
Run Code Online (Sandbox Code Playgroud)
但它没有用......
考虑使用列表理解:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
或麻木:
>>> 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])
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因需要使用手动循环:
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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |