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

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

Currently, I save the dates in different lists for the day and month, and then zipthem in the date list ... so the date list might look something like this:

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

My problem is that I need to extract duplicate tuples to another list, and not just delete them using 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 make a list of dates in dictionaryand then add it to the elements again, but I ask if there is an easier way. Any suggestions?

+4
source share
3 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 cheats, not one of them, use a counter as well as a key.

If you care about the initial order, do the same, but use OrderedCounter:

>>> from collections import Counter, OrderedDict
>>> class OrderedCounter(Counter, OrderedDict): 
...     pass
+6
source

You can use collections.Counteralong with the following expression:

>>> from collections import Counter
>>> my_list = [(2,3),(2,3),(4,8)]

>>> my_counter = Counter(my_list)
>>> [k for k, v in my_counter.items() if v>1]
[(2, 3)]

Alternatively, you can also get the desired result with set()along with list.count()(Note: this method is less efficient):

>>> my_set = set(my_list)  # To get unique tuples
#            count of each tuple  v
>>> [t for t in my_set if my_list.count(t) > 1]
[(2, 3)]
+2
source

.count(), , >1:

[date for date in dates if dates.count(date)>1]

set() list:

new_list=list(set([date for date in dates if dates.count(date)>1]))

:

[(2,3)]
+1

Source: https://habr.com/ru/post/1667054/


All Articles