Finger twist
Finger twist

Reputation: 3786

adding elements in nested lists

I have got a list containing nested lists like this :

[ [datetime.datetime(2000, 12, 10, 0, 0), 0.0011] , [datetime.datetime(2000, 12, 11, 0, 0), 0.0013 , [datetime.datetime(2000, 12, 12, 0, 0), 0.0014]]

etc..

How do I go about adding sub elements 2 by 2 like this :

sum(0.0011,0.0013) + 0.0014

then taking the result of this sum and adding it to the next sub element ?

I`m basically trying to compound the values .

thanks!

Upvotes: 0

Views: 99

Answers (2)

Gareth Latty
Gareth Latty

Reputation: 88977

The easiest way to do this is with the sum() builtin and a generator expression:

>>>items = [[datetime.datetime(2000, 12, 10, 0, 0), 0.0011], [datetime.datetime(2000, 12, 11, 0, 0), 0.0013 ], [datetime.datetime(2000, 12, 12, 0, 0), 0.0014]]
>>>sum(item[1] for item in items)
0.0038000000000000004

Edit:

If you want to print out the result of each stage of the summation, you want to use functools.reduce() (which, in 2.x is the reduce builtin).

from functools import reduce
import datetime

items = [[datetime.datetime(2000, 12, 10, 0, 0), 0.0011], [datetime.datetime(2000, 12, 11, 0, 0), 0.0013 ], [datetime.datetime(2000, 12, 12, 0, 0), 0.0014]]

def add_printing_result(a, b):
    total = a+b
    print(total)
    return total

reduce(add_printing_result, (item[1] for item in items))

Which gives us:

0.0024000000000000002
0.0038000000000000004

Upvotes: 2

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

sum = 0, myarr = [ [datetime.datetime(2000, 12, 10, 0, 0), 0.0011] , [datetime.datetime(2000, 12, 11, 0, 0), 0.0013] , [datetime.datetime(2000, 12, 12, 0, 0), 0.0014]]

for(i in myarr):
    sum+=i[1]

I'm sure there are better ways to do this (I'm no Python expert) but this should sum your values properly such that sum is the sub elements' sum.

Upvotes: 0

Related Questions