Counting duplicate integers in Python

How to find the total number of duplicates in a row? those. if he was j= [1,1,1,2,2,2] would he find duplicates of 4 ? I could only find an account that shows how many times each individual number was accounted for.

+6
python duplicates count
source share
2 answers
 >>> j= [1,1,1,2,2,2] >>> len(j) - len(set(j)) 4 

and btw, j is a list, not a string, although this does not really matter for this exercise.

+17
source share

It seems like a popular answer already exists, but if you also want to support separate duplicates, the new Counter() collection object in Python 2.7 is perfect for this.

 >>> from collections import Counter >>> j = [1,1,1,2,2,2] >>> Counter(j) Counter({1: 3, 2: 3}) >>> sum([i - 1 for i in c.values() if i > 1]) 4 >>> {k: v - 1 for k, v in c.items()} # individual dupes {1: 2, 2: 2} 

There is a backport for Counter in ActiveState

+7
source share

All Articles