Modify passed, nested dict/list

Posted by Gerenuk on Stack Overflow See other posts from Stack Overflow or by Gerenuk
Published on 2011-02-06T20:24:03Z Indexed on 2011/02/06 23:25 UTC
Read the original article Hit count: 225

Filed under:

I was thinking of writing a function to normalize some data. A simple approach is

def normalize(l, aggregate=sum, norm_by=operator.truediv):
    aggregated=aggregate(l)
    for i in range(len(l)):
        l[i]=norm_by(l[i], aggregated)

l=[1,2,3,4]
normalize(l)
l -> [0.1, 0.2, 0.3, 0.4]

However for nested lists and dicts where I want to normalize over an inner index this doesnt work. I mean I'd like to get

l=[[1,100],[2,100],[3,100],[4,100]]
normalize(l, ?? )
l -> [[0.1,100],[0.2,100],[0.3,100],[0.4,100]]

Any ideas how I could implement such a normalize function?

Maybe it would be crazy cool to write

normalize(l[...][0])

Is it possible to make this work?? Or any other ideas?

Also not only lists but also dict could be nested. Hmm...

EDIT: I just found out that numpy offers such a syntax (for lists however). Anyone know how I would implement the ellipsis trick myself?

© Stack Overflow or respective owner

Related posts about python