栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

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

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]

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661312.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号