vascop
vascop

Reputation: 5222

Get tuples with max value from each key from a list

I have a list of tuples like this:

[(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]

I want to keep the tuples which have the max first value of every tuple with the same second value. For example (2, 1) and (3, 1) share the same second (key) value, so I just want to keep the one with the max first value -> (3, 1). In the end I would get this:

[(1, 0), (3, 1), (6, 2), (2, 3)]

I don't mind at all if it is not a one-liner but I was wondering about an efficient way to go about this...

Upvotes: 3

Views: 3800

Answers (4)

ovgolovin
ovgolovin

Reputation: 13430

from operator import itemgetter
from itertools import groupby

[max(items) for key, items in groupby(L,key = itemgetter(1))]

It's assuming that you initial list of tuples is sorted by key values.

groupby creates an iterator that yields objects like (0, <itertools._grouper object at 0x01321330>), where the first value is the key value, the second one is another iterator which gives all the tuples with that key.

max(items) just selects the tuple with the maximum value, and since all the second values of the group are the same (and is also the key), it gives the tuple with the maximum first value.

A list comprehension is used to form an output list of tuples based on the output of these functions.

Upvotes: 6

KQ.
KQ.

Reputation: 922

Probably using a dict:

rd = {}
for V,K in my_tuples:
  if V > rd.setdefault(K,V):
    rd[K] = V
result = [ (V,K) for K,V in rd.items() ]

Upvotes: 4

James Felix Black
James Felix Black

Reputation: 300

You could use a dictionary keyed on the second element of the tuple:

l = [(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]
d = dict([(t[1], None) for t in l])
for v, k in l:
  if d[k] < v:
    d[k] = v 
l2 = [ (v, k) for (k, v) in d.items() if v != None ]
print l2

Upvotes: 0

Debilski
Debilski

Reputation: 67888

import itertools
import operator
l = [(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]
result = list(max(v, key=operator.itemgetter(0)) for k, v in itertools.groupby(l, operator.itemgetter(1)))

Upvotes: 0

Related Questions