简体   繁体   中英

How to loop through a list where data points are dependent on each other?

I have a list, a = [5, 4, 9, 3, 6, 6, 8, 2], and I essentially want to sum the first three numbers, and that sum will be the first value in the new list. The next value in the new list will be the sum of 4, 9, and 3...etc. etc. How to loop this in Python?

list slicing is a good method.

all you need to do is travese from start index to end index-2 , ( can make sum of last 3 element and when you reach second last or last ement you wont be able to take 3 elemnts)

here you can take 3 elemnts and using list slicing, slice list from the current index to next 3 index ie a[i:i+3] where [i,i+3) is range. then on that new list performing sum operation and appending the reuslt to final list.

a = [5, 4, 9, 3, 6, 6, 8, 2]
res=[]
for i in range(len(a)-2):
    res.append(sum(a[i:i+3]))

print(res)

output

[18, 16, 18, 15, 20, 16]

One liner:

list(map(sum, zip(a, a[1:], a[2:])))

Output:

[18, 16, 18, 15, 20, 16]

So you are creating the required sublists of the numbers you want to add up and then you sum each sublist using the high-order function map .

如果我了解您想要什么:

b = [sum(a[i : i+3]) for i in range(0, len(a)-2)]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM