在Python列表中查找并返回重复值的名称和计数

时间:2013-10-21 00:25:06

标签: python dictionary

我有一个值列表,表示一段正则表达式在字符串中匹配的次数。从这里,我想找到不止一次出现的数字及其数量。例如,对于[2, 2, 2, 0, 2, 1, 3, 3]我希望{2:4,3:2}作为输出(如果它在dict中)或[[2,4],[3,2]]如果它在列表列表中。我正在寻找最快,最简洁的方法来做到这一点。现在,我通过以下代码完成,但认为这是详细的最佳方式。

numWinners=[2, 2, 2, 0, 2, 1]
tieCount={x:numWinners.count(x) for x in numWinners}
ties=dict()
for key, value in tieCount.items():
    if value>1:
        ties[key]=value

print ties
{2: 4, 3: 2}

列表或字典输出对我来说不是一个问题 - 再次,无论是最快还是简洁。

3 个答案:

答案 0 :(得分:5)

我将collections.Counter与字典理解结合起来选择重复项:

>>> from collections import Counter
>>> numWinners = [2, 2, 2, 0, 2, 1, 3, 3]
>>> counts = Counter(numWinners)
>>> {k: v for k,v in counts.items() if v > 1}
{2: 4, 3: 2}

答案 1 :(得分:2)

您可以使用dict理解来创建直方图:

>>> ns=[2, 2, 2, 0, 2, 1, 3, 3]
>>> {x: ns.count(x) for x in set(ns) if ns.count(x) > 1}
{2: 4, 3: 2}

答案 2 :(得分:0)

尝试使用collections.defaultdict

import collections
ties = collections.defaultdict(lambda:0)
for num in numWinners:
     ties[num] = ties[num]+1


 for key,value in ties.iteritems():
     print key, value