我正在使用python。有没有一种方法可以计算使用一个以上的键在一个字典中找到值的次数,然后返回一个计数?

因此,例如,如果我有50个值,并且运行了一个脚本来执行此操作,那么我将得到一个看起来像这样的计数:

1: 23
2: 15
3: 7
4: 5

上面的内容告诉我,1个键中出现23个值,2个键中出现15个值,3个键中出现7个值,4个键中出现5个值。

另外,如果我的字典中每个键有多个值,此问题是否会改变?

这是我的字典的一个样本(它是细菌名称):
{'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']}
因此,从此示例中,有8个唯一值,我将得到的理想反馈是:
1:4
2:3
3:1

因此,一个键中只有4个细菌名称,两个键中只有3个细菌,三个键中只有1个细菌。

最佳答案

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

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

    我采取的方法不太优雅,其他方法都无法解决,但已将问题分解为单独的步骤:
    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 occurs
    vals = {}                       # 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 it
    print 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 count
    for 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]
    

    您也可以test this code on codepad

    关于python - 计算用一个以上的键找到一个字典值的次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18582370/

    10-12 16:41