Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of duplicate tuples inside a list

Tags:

python

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
like image 305
shadowrain Avatar asked Oct 25 '19 07:10

shadowrain


1 Answers

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}
like image 111
seymourgoestohollywood Avatar answered Oct 04 '22 04:10

seymourgoestohollywood