Issue
I have the following list:
list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805]
And I want to add the numbers to the first number into the new list like this:
list_2 = []
list_2[0] = list_1[0]
list_2[1] = list_1[0] + list_1[1]
list_2[2] = list_1[0] + list_1[1] + list_1[2]
list_2[3] = list_1[0] + list_1[1] + list_1[2] + list_1[3]
list_2[4] = list_1[0] + list_1[1] + list_1[2] + list_1[3] + list_1[4]
How can I make this with a for loop or something more practical?
Solution
You can use itertools.accumulate
:
from itertools import accumulate
list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805]
list_2 = list(accumulate(list_1))
print(list_2)
Prints:
[2.03898103, 4.2760684399999995, 5.95828417, 7.08181302, 7.64409107]
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.