Python帶有一個計數器類包括:collections.Counter()
:
from collections import Counter
site_counts = Counter(value[0] for value in inputdict.values())
演示:
>>> from collections import Counter
>>> inputdict = {'B': ['J', 'K', 'L'], 'C': ['K', 'J', 'L'], 'A': ['L', 'K', 'J'], 'D': ['J', 'L', 'K'], 'E': ['L', 'J', 'K']}
>>> site_counts = Counter(value[0] for value in inputdict.values())
>>> site_counts
Counter({'J': 2, 'L': 2, 'K': 1})
Counter
是一本字典的子類,所以你可以只在鍵盤上環,現在並打印出計數相關聯,但您也可以通過使用計數(降序)通過使用Counter.most_common()
method:
print('Site Counts:')
for site, count in site_counts.most_common():
print(' {} got {:2d} hits'.format(site, count))
哪些用於您的樣品輸入打印:
Site Counts:
J got 2 hits
L got 2 hits
K got 1 hits