Python 对列表中的连续元素对求和

Python 对列表中的连续元素对求和,python,list,Python,List,我想通过index0,index1和index1,index2和index2,index3,等等来找到列表中元素的总和 比如: 您只需迭代索引: 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] 对于功能解决方案,您可以使用zip和sum: # don't shadow the built-in `list` l = [7

我想通过index0,index1和index1,index2和index2,index3,等等来找到列表中元素的总和

比如:


您只需迭代索引:

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]

对于功能解决方案,您可以使用
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]
这很好:)

list=[7,5,9,4,7,11]
aspSum=[]
i=0

虽然我是iPardon,但我仍在学习如果这两种方法都可用的话,哪种方法是推荐的方法,zip/map组合还是列表理解?不要问,因为一些上级给了我一个答案,让我用for循环而不是zip映射来回答问题,不是因为我不知道,而是他说我们应该始终使用最佳实践,我刚刚看到了你的做法,你似乎在游戏中非常深入,我正在寻找意见。谢谢。这是我的解决办法。但是你能解释一下切片部分吗,比如l[1:],我知道list[start:end,step],我用它来创建邻居。就在REPL里做吧。其基本切片。相关:
# 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]
list=[7,5,9,4,7,11]
aspSum = []
i = 0
while i<len(list)-1:
   aspSum.append(list[i]+list[i+1])
   i+=1