Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract duplicate tuples within a list in Python?

I am writing a program where I need to find same dates...

I currently store the dates on different lists for day and month and then zip them to a date list... so the date list might look something like this:

[(2,4),(4,18),(10,7)]

My problem is I need to extract the duplicate tuples to another list not just eliminate them with some set() or so.

If my date list gets [(2,3),(2,3),(4,8)] I need to get (2,3) to a new list.

Alternatively I could form the date list into a dictionary and then piece it again in items but I am asking if there is a simpler way. Any suggestions?

like image 436
agios Avatar asked Jan 05 '23 17:01

agios


1 Answers

You can use a counter for this task:

>>> from collections import Counter
>>> L = [(2,3),(2,3),(4,8)]
>>> [k for k,count in Counter(L).items() if count > 1]
[(2, 3)]

If you want all the dupes, rather than one of each, then use the count as well as the key.

If you care about the original ordering, do the same thing but using an OrderedCounter instead:

>>> from collections import Counter, OrderedDict
>>> class OrderedCounter(Counter, OrderedDict): 
...     pass
like image 86
wim Avatar answered Jan 07 '23 08:01

wim