【问题标题】:Python: Counting repeating values of a dictionaryPython:计算字典的重复值
【发布时间】:2011-03-30 17:48:34
【问题描述】:

我有一本字典如下:

dictA = { ('unit1','test1') : 'alpha' , ('unit1','test2') : 'beta', ('unit2','test1') : 'alpha', ('unit2','test2') : 'gamma' , ('unit3','test1') : 'delta' , ('unit3','test2') : 'gamma'   }

如何计算每个测试的重复值数量,与单位无关?

在 'test1' 中有 2x 'alpha',1x 'delta'

在 'test2' 中有 1x 'beta',2x 'gamma'

任何输入?

非常感谢。

【问题讨论】:

    标签: python dictionary count repeat


    【解决方案1】:

    在 Python 2.7 或 3.1 或更高版本中,您可以使用collections.Counter

    from collections import Counter
    counts = Counter((k[1], v) for k, v in dictA.iteritems())
    print(counts)
    

    打印

    Counter({('test1', 'alpha'): 2, ('test2', 'gamma'): 2, ('test2', 'beta'): 1, ('test1', 'delta'): 1})
    

    【讨论】:

    • 在以前的版本中,collections.defaultdict(int) 的工作方式类似。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2019-02-05
    相关资源
    最近更新 更多