jc315
jc315

Reputation: 61

How to get the max value from list of tuples of tuples (?)

My data looks something like this:

I have a list d where

d = [(0, [(1, 0.15122674), (2, 0.59446937), (3, 0.06613562), (4, 0.1877523)]),
    (1, [(1, 0.46739018), (4, 0.5283537)]),
    (2, [(1, 0.99668014)])]

I would like to have an output of:

[(0, [(2, 0.59446937)]),
(1, [(4, 0.5283537)]),
(2, [(1, 0.99668014)])]

Where we are taking the max value, looking at the 2nd value of these tuples.

I'm not too sure where to start because I am python beginner. I understand if this was a simple list of tuples we could do something like:

max(d,key=lambda x:x[1])

but given the structure of my data, I'm not too sure how to go about this one...

Upvotes: 1

Views: 42

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

You can use a list comprehension and operator.itemgetter to make it much easier:

In [9]: from operator import itemgetter

In [10]: [(i, max(j, key=itemgetter(1))) for i, j in d]
Out[10]: [(0, (2, 0.59446937)), (1, (4, 0.5283537)), (2, (1, 0.99668014))]

Upvotes: 1

Related Questions