Home > database >  Python - List sum up every value before from another list
Python - List sum up every value before from another list

Time:06-24

I'm looking for a way in python to create a list from another list but always add every value before.

For example i want to create List2 from List1

List1 = [100, 100, 0, 100, 100, 0, 100, 100, 0]

List2 = [100, 200, 200, 300, 400, 400, 500, 600, 600]

So i always want to add all values before.

I hope it's understandable.

Thank you for every advice.

CodePudding user response:

You could use accumulate from the standard library module itertools:

from itertools import accumulate

list1 = [100, 100, 0, 100, 100, 0, 100, 100, 0]
list2 = list(accumulate(list1))

gives you

[100, 200, 200, 300, 400, 400, 500, 600, 600]

as list2.

CodePudding user response:

Just loop once through the list, adding to each element the one that came before it. This carries down the list, so eventually each element will be a sum of the ones that came before it.

list2 = list1
for i in range(1, len(list1)):
    list2[i]  = list2[i-1]

Hope this helps!

CodePudding user response:

Maybe something like this:

>>> List1 = [100, 100, 0, 100, 100, 0, 100, 100, 0]
>>> list2 = [sum(List1[:i 1]) for i in range(len(List1))]


>>> list2
[100, 200, 200, 300, 400, 400, 500, 600, 600]

CodePudding user response:

i create this function can help i guess

def func(list):
    list2 = []
    list2.append(list[0])
    for i in range(1,len(list)):
        x = list[i] list2[i-1]
        list2.append(x)    
    return list2
  • Related