Now I have a list a = [1,2,3]
. How could I get result [1,3,6]
only using one line code?
I can achive it like this , but I want use one line code.
k=0
arr = []
a = [1,2,3]
for i in a:
k+=i
arr.append(k)
print(arr)
Now I have a list a = [1,2,3]
. How could I get result [1,3,6]
only using one line code?
I can achive it like this , but I want use one line code.
k=0
arr = []
a = [1,2,3]
for i in a:
k+=i
arr.append(k)
print(arr)
a = [1,2,3]
arr = [sum(a[:i + 1]) for i in range(len(a))]
print(arr)
If you really want to do it in one line and efficiently, you can use itertools.accumulate
:
In [1]: import itertools
In [2]: a = [1, 2, 3]
In [3]: list(itertools.accumulate(a))
Out[3]: [1, 3, 6]