theMobDog theMobDog - 1 year ago 70
Python Question

Python: from list to enumerated list to pass to lambda reduce function

I am trying to pass a list of hex char, into a lambda function, reduce to calculate a total decimal value. I am not sure what I am doing wrong but the python interpreter wouldn't recognize list(enumerate(reversed(numList)) as a list of tuples.

numList = ['3', '0', 'e', 'f', 'e', '1']
reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,

when I print out


It is a list of tuples.

[(0, '1'), (1, 'e'), (2, 'f'), (3, 'e'), (4, '0'), (5, '3')]

But it spit our error: can only concatenate tuple (not "int") to tuple


The code is now working with a minor addition ",0" added to the lambda

reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,

I don't understand what that means. Also I am not sure what is the best way to approach this.

that means you make sure, that it starts with 0 instead of the first Argument - in this case (0,'1') - because otherwise the types dont match? – am2 1 min ago


the third argument you add is initializer. without it, the sum in first iteration will be (0,'1'). so you were trying to evaluate (0,'1')+int(x,16)*16**up which is invalid. – ymonad 14 mins ago


reduce(lambda sum,(up,x):sum+ int(x,16)*16**up,enumerate(reversed(numList)),0)

is just as good and
returns iter and
is redundant.

Marked it as solved.

Answer Source

You don't need to use the generic reduce function when all you really need is to calculate the sum.

This works and is vastly simpler:

sum( int(x,16)*16**up for up,x in enumerate(reversed(numList)) )

Also, I'm going to guess you already know you can do the exact same thing like this:

int(''.join(numList), 16)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download