I have a list name:
my_list = [1,2,3,4,5,6]
I want to output to look like this, 1, 3(1+2),6(1+2+3), 10(1+2+3+4), ...
how can I do this in python? Thank for reply in advance
I have a list name:
my_list = [1,2,3,4,5,6]
I want to output to look like this, 1, 3(1+2),6(1+2+3), 10(1+2+3+4), ...
how can I do this in python? Thank for reply in advance
In Python 3.2+ it's as simple as this:
>>> from itertools import accumulate
>>> nums = [1,2,3,4,5,6]
>>> list(accumulate(nums))
[1, 3, 6, 10, 15, 21]
total = 0
for i, element in enumerate(my_list):
total += element
print "%d (%s)" % (total, '+'.join(my_list[:i+1])
Try this one-liner:
b = [sum(a[:i+1]) for i, x in enumerate(a)]
This is not super-efficient (and that's an understatement), because you are summing again and again the entire elements...
for a more efficient solution you can do something like this:
result = []
for i, current in enumerate(a):
if result:
last = result[i - 1]
else:
last = 0
result.append(last + current)
print(result)
>> [1, 3, 6, 10, 15, 21]