python - 计算使用多个键找到字典值的次数

标签 python dictionary

我在 python 工作。有没有一种方法可以计算字典中的值被多个键找到的次数,然后返回一个计数?

因此,例如,如果我有 50 个值,并且我运行一个脚本来执行此操作,我将得到一个如下所示的计数:

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

以上会告诉我 23 个值出现在 1 个键中,15 个值出现在 2 个键中,7 个值出现在 3 个键中,5 个值出现在 4 个键中。

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

这是我的字典示例(它是细菌名称):

{'0': ['Pyrobaculum'], '1': ['分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌', '分枝杆菌'], '3': ['Thermoanaerobacter', 'Thermoanaerobacter'], '2': ['螺杆菌', 'Mycobacterium'], '5': ['Thermoanaerobacter', 'Thermoanaerobacter'], '4': ['Helicobacter'], '7': ['Syntrophomonas'], '6': ['Gelria'] , '9': ['弯曲杆菌', '弯曲杆菌'], '8': ['Syntrophomonas'], '10': ['脱硫杆菌', '分枝杆菌']}

所以从这个示例中,有 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/

相关文章:

通过 POST 使用请求库进行 python 身份验证

Python libass 还是 VapourSynth?

python - 将打印重定向到字符串列表?

python - 尝试提取数据时不断收到 401 错误

python - AWS BotoCore 错误 - AttributeValue 不能包含空字符串

Swift 在字典中允许 nil

Python:如何通过切片插入列表?

c# - 按键排序字典?

PHP 索引数组的 Java 替代品

dictionary - 如何从 Ansible 字典中删除单个键?