Reputation: 1
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.
Upvotes: 0
Views: 322
Reputation: 389
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.copy()
for i in range(1, len(list1)):
list2[i] += list2[i-1]
Hope this helps!
Upvotes: 0
Reputation: 11321
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
.
If you don't like that I'd suggest something like:
list2 = [list1[0]]
for number in list1[1:]:
list2.append(list2[-1] + number)
Upvotes: 2
Reputation: 139
i create this function can help i guess
def func(ur_list):
list2 = []
list2.append(list[0])
for i in range(1,len(list)):
x = list[i]+list2[i-1]
list2.append(x)
return list2
Upvotes: 0
Reputation: 164
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]
Upvotes: 0