2015-04-14 35 views
0

我在Python,用於跟蹤客戶分析的,看起來像這樣計算python和打印中的第一個元素?

'B': ['J'], 'C': ['K'], 'A': ['L'], 'D': ['J'], 'E': ['L'] 

我試圖打印這樣一個表的數據結構:

Site Counts: 
    J got 2 hits 
    K got 1 hits 
    L got 2 hits 

到目前爲止,我還以爲使用.fromkeys()方法,但對於如何獲取數據沒有太多的想法,我已經嘗試了很多不同的東西,並沒有在這個問題上運氣。

回答

2

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 
相關問題