views:

57

answers:

2

I have a list of nested tuples of the form:

[(a, (b, c)), ...]

Now I would like to pick the element which maximizes a while minimizing b and c at the same time. For example in

[(7, (5, 1)), (7, (4, 1)), (6, (3, 1))]

the winner should be

(7, (4, 1))

Any help is appreciated.

+3  A: 
>>> max(lst, key=lambda x: (x[0], -x[1][0], -x[1][1]))
(7, (4, 1))
SilentGhost
+3  A: 

In my understanding, you want to sort decreasingly by a, and ascendingly by b, then by c. If that's right, you can do it like so:

>>> l=[(7, (5, 1)), (7, (4, 1)), (6, (3, 2)), (6, (3, 1))]
>>> sorted(l, key = lambda x: (-x[0], x[1]))
[(7, (4, 1)), (7, (5, 1)), (6, (3, 1)), (6, (3, 2))]

Picking the "winner" would be as simple as picking the first element.

If b and c should be summed up, it would simply be sum(x[1]) instead of x[1] in my example.

My key function returns a tuple because Python correctly sorts tuples containing multiple elements:

>>> sorted([(1,2), (1,1), (1,-1), (0,5)])
[(0, 5), (1, -1), (1, 1), (1, 2)]
AndiDog
`max` has `key` parameter, so there is no need to create an intermediate list. The signs of course would need to be reversed.
SilentGhost
@SilentGhost: Of course the `max` function is a good idea here. I wanted to point out that, depending on the problem (or homework) the OP is trying to solve, it might be necessary to pick multiple items. Therefore, a presorted list would be better.
AndiDog
@AndiDog: It is actually a real problem and no homework. Thanks anyway.
mathias