user14263018
user14263018

Reputation:

How to cumsum all values at tuple index n, from a list of tuples?

In the following code I want to add second parameters of list=[(0,3),(2,6),(1,10)] in a for loop. first iteration should be 3+6=9 and the second iteration should add output of previous iteration which is 9 to 10---> 9+10=19 and I want final output S=[9,19]. I am not sure how to do it, Should I add another loop to my code?

T=[(0,3),(2,6),(1,10)]
S=[]
for i in range(len(T)):
    b=T[0][i]+T[0][i+1]
    S.append(b)

Upvotes: 1

Views: 664

Answers (5)

Trenton McKinney
Trenton McKinney

Reputation: 62463

T = [(0,3),(2,6),(1,10)]
T = list(zip(*T))

print(T)
[out]:
[(0, 2, 1), (3, 6, 10)]

# use an assignment expression to sum T[1]
total = T[1][0]  # 3
S = [total := total + v for v in T[1][1:]]

print(S)
[out]:
[9, 19]

Upvotes: 1

englealuze
englealuze

Reputation: 1663

Here is a solution with native recursion

import operator
mylist =[(0,3),(2,6),(1,10)]

def accumulate(L, i, op):
  def iter(result, rest, out):
    if rest == []:
      return out
    else:
      r = op(result, rest[0][i-1])
      return iter(r, rest[1:], out + [r])
  return iter(L[0][i-1], L[1:], [])

print(accumulate(mylist, 2, operator.add))
print(accumulate(mylist, 1, operator.add))
print(accumulate(mylist, 2, operator.mul))

# ==>
# [9, 19]
# [2, 3]
# [18, 180]

Upvotes: 0

Abin K Paul
Abin K Paul

Reputation: 181

Just modify your code as below

T=[(0,3),(2,6),(1,10)]
S=[]
b = T[0][1]
for i in range(1,len(T)):
    b+=T[i][1]
    S.append(b)

Upvotes: 0

buran
buran

Reputation: 14253

use itertools.accumulate

spam = [(0,3),(2,6),(1,10)]

from itertools import accumulate
print(list(accumulate(item[-1] for item in spam))[1:])

output

[9, 19]

Upvotes: 2

Sushil
Sushil

Reputation: 5531

This should help u:

T=[(0,3),(2,6),(1,10)]

lst = [T[i][1] for i in range(len(T))]

final_lst = []

for x in range(2,len(lst)+1):
    final_lst.append(sum(lst[:x]))

print(final_lst)

Output:

[9, 19]

If u prefer list comprehension, then use this line instead of the last for loop:

[final_lst.append(sum(lst[:x])) for x in range(2,len(lst)+1)]

Output:

[9, 19]

Upvotes: 0

Related Questions