I want to count the number of duplicated tuples in a list.
For example num_list:
num_list = [(3,14),(2,8),(10,25),(5,17),(3,2),(7,25),(4,30),(8,7),(int(2),8),(1,22)]
I want to return the result: Total duplicates: 1
which is the (2, 8)
pair.
what i have so far is not very efficient, so I am wondering if there's a more efficient way to do this?
count = 0
for a in num_list:
for b in num_list:
if a is b:
continue
if a[0] == b[0] and a[1] == b[1]:
count += 1
num_list = [(3,14),(2,8),(10,25),(5,17),(3,2),(7,25),(4,30),(8,7),(int(2),8),(1,22)]
dupe_count = len(num_list) - len(set(num_list))
print(dupe_count)
If you cared about the actual items appearing more than once, the most efficient way is to use Counter
:
from collections import Counter
c = Counter(num_list)
c = {k: v for k, v in c.items() if v > 1}
print(c)
Gives a dict
of items appearing more than once and their frequency:
{(2, 8): 2}
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