计算用一个以上的键找到一个字典值的次数

计算用一个以上的键找到一个字典值的次数,第1张

计算用一个以上的键找到一个字典值的次数

因此,除非我读错了,否则您想知道:

  • 对于原始字典中的每个值,每个不同的值计数会出现多少次?
  • 本质上 ,您想要的是 字典中值 频率

我采用了其他方法无法回答的优雅方法,但已将问题分解为各个步骤:

d = {'0': ['Pyrobaculum'], '1': ['Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium'], '3': ['Thermoanaerobacter', 'Thermoanaerobacter'], '2': ['Helicobacter', 'Mycobacterium'], '5': ['Thermoanaerobacter', 'Thermoanaerobacter'], '4': ['Helicobacter'], '7': ['Syntrophomonas'], '6': ['Gelria'], '9': ['Campylobacter', 'Campylobacter'], '8': ['Syntrophomonas'], '10': ['Desulfitobacterium', 'Mycobacterium']}# Iterate through and find out how many times each key occursvals = {} # A dictonary to store how often each value occurs.for i in d.values():  for j in set(i):   # Convert to a set to remove duplicates    vals[j] = 1 + vals.get(j,0) # If we've seen this value iterate the count          # Otherwise we get the default of 0 and iterate itprint vals# Iterate through each possible freqency and find how many values have that count.counts = {}          # A dictonary to store the final frequencies.# We will iterate from 0 (which is a valid count) to the maximum countfor i in range(0,max(vals.values())+1):    # Find all values that have the current frequency, count them    #and add them to the frequency dictionary    counts[i] = len([x for x in vals.values() if x == i])for key in sorted(counts.keys()):  if counts[key] > 0:     print key,":",counts[key]

您也可以在键盘上测试此代码。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5667428.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存