0

I have the following list value:

iva_versamenti_totale={'Liquidazione IVA': [sum(t) for t in zip(*iva_versamenti.values())],}

I want to obtain about the iva_versamenti_totale variable the following sum:

p0, p1+p0, p2+p1, p3+p2 and so on...

Ad example:

iva_versamenti_totale = {'Liquidazione IVA': [1,2,3,4,5],}
result={'Totals': [1,3,5,7,9],}

EDIT

I have tried the following code:

iva_versamenti_totale = [1,2,3,4,5]

results = [*map(sum, zip(iva_versamenti_totale , [0]+iva_versamenti_totale ))]

But if I try

iva_versamenti_totale = [1,0,0,0]

I want to obtain [1,1,1,1], instead I obtain [1,1,0,0]

  • 2
    This is not a cumulative sum. This is a sum of pairs. – timgeb May 08 '20 at 08:35
  • Better duplicate target: https://stackoverflow.com/questions/3849625/pairwise-traversal-of-a-list-or-tuple – timgeb May 08 '20 at 08:37
  • 1
    Does this answer your question? [pairwise traversal of a list or tuple](https://stackoverflow.com/questions/3849625/pairwise-traversal-of-a-list-or-tuple) – Brown Bear May 08 '20 at 08:42

2 Answers2

1

Another version:

l = [1,2,3,4,5]

s = [*map(sum, zip(l, [0]+l))]

print(s)

Prints:

[1, 3, 5, 7, 9]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • I have solved it with your answer. Just a last questio: if I want to set a filter that set at zero the negative value? Ad example if my print is `[ 1, 3, 5, -3 ]`give me `[ 1, 3, 5, 0 ] ?? –  May 08 '20 at 09:15
  • @Jfix91 if you want to set negative values in list to `0` you can do for example `print([max(0, v) for v in [1, 3, 5, -3]])` – Andrej Kesely May 08 '20 at 10:08
  • oKEY Thanks. I have noticed that your code don't save the values of previous i. Ad example: if I have `[1,0,0,0,0]` the result may be `[1,1,1,1,1]` instead [1,1,0,0,0] –  May 08 '20 at 10:46
0

You can try like :

a =  [1,2,3,4,5]
[a[i]+a[i-1] if i!=0 else a[i] for i in range(len(a))]
DARK_C0D3R
  • 2,075
  • 16
  • 21