-2

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)
Mortz
  • 4,654
  • 1
  • 19
  • 35

2 Answers2

2
a = [1,2,3] 
arr = [sum(a[:i + 1]) for i in range(len(a))] 
print(arr)
Ved Rathi
  • 327
  • 1
  • 12
1

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]
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175