Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: conditionally delete elements from list

Tags:

python

list

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.

  • The tuples could be two-element lists instead, if that makes a difference.
  • All elements are nonnegative integers.
  • I like the current answers. I should really learn more about what collections has to offer!
like image 879
Steve Tjoa Avatar asked Feb 03 '23 01:02

Steve Tjoa


1 Answers

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)]
like image 195
John La Rooy Avatar answered Feb 05 '23 16:02

John La Rooy