开发者

Counting Duplicates Integers in Python

How do I find the total number of duplicates in a string? i.e., if it was j= [1,1,1开发者_开发技巧,2,2,2] it would find 4 duplicates? I've only been able to find counting which shows how many times each individual number occurred.


>>> j= [1,1,1,2,2,2]
>>> len(j) - len(set(j))
4

and btw, j is a list and not a string, although for the purpose of this exercise it doesn't really matter.


There seems to be a popular answer already, but if you would like to maintain the individual duplicate counts as well, 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 at ActiveState

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜