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?
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
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