Suppose I have a list of tuples:
x = [(1,2), (3,4), (7,4), (5,4)]
Of all tuples that share the second element, I want to preserve the tuple with the largest first element:
y = [(1,2), (7,4)]
What is the best way to achieve this in Python?
Thanks for the answers.
collections
has to offer!Similar to Aaron's answer
>>> from collections import defaultdict
>>> x = [(1,2), (3,4), (7,4), (5,4)]
>>> d = defaultdict(int)
>>> for v,k in x:
... d[k] = max(d[k],v)
...
>>> y=[(k,v) for v,k in d.items()]
>>> y
[(1, 2), (7, 4)]
note that the order is not preserved with this method. To preserve the order use this instead
>>> y = [(k,v) for k,v in x if d[v]==k]
>>> y
[(1, 2), (7, 4)]
here is another way. It uses more storage, but has less calls to max, so it may be faster
>>> d = defaultdict(list)
>>> for k,v in x:
... d[v].append(k)
...
>>> y = [(max(k),v) for v,k in d.items()]
>>> y
[(1, 2), (7, 4)]
Again, a simple modification preserves the order
>>> y = [(k,v) for k,v in x if max(d[v])==k]
>>> y
[(1, 2), (7, 4)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With