I want to find sums of elements of the list by index0,index1 and index1,index2 and index2,index3, and so on.
Like:
my_list = [7, 5, 9, 4, 7, 11]
sums = [12, 14, 13, 11, 18] # 7+5, 5+9, 9+4, 4+7, 7+11
You just have to iterate through the indices:
l = [7, 5, 9, 4, 7, 11]
res = [l[i] + l[i+1] for i in range(len(l)-1)]
print(res)
Output:
[12, 14, 13, 11, 18]
You can use zip
and sum
for a functional solution:
# 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]
This works fine :)
list=[7,5,9,4,7,11]
aspSum = []
i = 0
while i<len(list)-1:
aspSum.append(list[i]+list[i+1])
i+=1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.