我的最后一个问题是 adding two consecutive numbers in a list .但答案并非一概而论。如何在n 连续元素中添加 一个列表。其中 n >= 2
if n = 3
l = [1,2,3,4,5,6] result = [6, 15]
l = [1,2,3,4,5,6,7] result = [6, 15, 7]
l = [1,2,3,4,5,6,7,8] result = [6, 15, 15]
if n = 4
l = [1,2,3,4,5,6,7] result = [10, 18]
请您参考如下方法:
n=numConsecutiveElements
[sum(list[x:x+n]) for x in range (0,len(list),n)]
会成功的
代码说明
x=0 //Start at the first element
while(x<len(list)): // Until we get to the end of the list
sum(list[x] + list[x+1] + ... list[x+n-1]) //Sum n elements
x+=n //Move The first element n elements forward
