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.
j= [1,1,1,2,2,2]
4
>>> 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.
j
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.
Counter()
>>> 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