因此,除非我读错了,否则您想知道:
- 对于原始字典中的每个值,每个不同的值计数会出现多少次?
- 本质上 ,您想要的是 字典中值 的 频率
我采用了其他方法无法回答的优雅方法,但已将问题分解为各个步骤:
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]
您也可以在键盘上测试此代码。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)