Python:计算字典的重复值 [英] Python: Counting repeating values of a dictionary

查看:340
本文介绍了Python:计算字典的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典如下:

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

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





< 'test2'中有2x'alpha',1x'delta'



有1x'beta',2x'gamma'



任何输入?



很感谢。

解决方案

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

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

列印

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


I have a dictionary as follows:

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

How can I count the number of repeating values per each test independent of units?

i.e.

in 'test1' there is 2x 'alpha', 1x 'delta'

in 'test2' there is 1x 'beta', 2x 'gamma'

Any inputs?

Many Thanks.

解决方案

In Python 2.7 or 3.1 or above, you can use collections.Counter:

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

prints

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

这篇关于Python:计算字典的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆