我想找到索引2,index3和index3,index4和index4,index5等的列表元素的总和
喜欢:
list=[7,5,9,4,7,11]
aspSum=[12,14,13,11,18] ## 7+5, 5+9, 9+4, 4+7, 7+11
答案 0 :(得分:4)
您只需要遍历索引:
l = [7, 5, 9, 4, 7, 11]
res = [l[i] + l[i+1] for i in range(len(l)-1)]
print(res)
输出:
[12, 14, 13, 11, 18]
答案 1 :(得分:3)
您可以将zip
和sum
用于功能解决方案:
# don't shadow the built-in `list`
l = [7,5,9,4,7,11]
# generate all neighboring pairs
pairs = zip(l, l[1:])
# generate all sums of pairs
sums = list(map(sum, pairs))
print(sums) # [12, 14, 13, 11, 18]
答案 2 :(得分:1)
这很好用:)
list=[7,5,9,4,7,11]
aspSum = []
i = 0
while i<len(list)-1:
aspSum.append(list[i]+list[i+1])
i+=1