2016-03-05 140 views
3

我有以下字典中的項目:如何從字典蟒蛇

Counter({'L': 233, 'T': 208, 'I': 169, 'G': 167, 'V': 161, 'N': 155, 'R': 151, 'S': 149, 'K': 148, 'E': 146, 'A': 144, 'Q': 131, 'P': 97, 'D': 92, 'W': 92, 'Y': 85, 'C': 80, 'F': 78, 'M': 52, 'H': 44})

現在我想要做一些計數它。但它不會工作。我想從3個最高值和3個最低值中總共得到%。比我要打印這樣的:

print("number 1 is:", <highestvalue>, "with this %:", <%fromhighestvalue>)

我的總和,使其在%,但由於未列出的字典,他用錯誤的值計算。我現在這個爲最高值:

def most(total, som): 

    a = som[list(som)[0]] 
    b = som[list(som)[1]] 
    c = som[list(som)[2]] 

    first = (a*100)/total 
    seccond = (b*100)/total 
    third = (c*100)/total 

    firstKey = list(som.keys())[list(som.values()).index(a)] 
seccondKey = list(som.keys())[list(som.values()).index(b)] 
thirdKey = list(som.keys())[list(som.values()).index(c)] 

return first, seccond, third, firstKey, seccondKey, thirdKey` 

任何人都可以幫助我嗎?

這是現在的結果:

first: F Procentaantal: 3.020914020139427 
seccond: R Procentaantal: 5.848179705654531 
third: D Procentaantal: 3.563129357087529 
+0

我需要在哪裏使用它?因爲我不會在我現在的代碼中工作 –

回答

4

類似的東西來這應該工作:

topandlow = [(k, 100 * v/sum(som.values())) for k, v in som.most_common()[:3] + som.most_common()[-3:]] 
for k, v in topandlow: 
    print(k, "Procentaantal: ", v) 
+1

太棒了,這正是我需要的。謝謝 –

+0

'most_common()'也接受一個數字,所以第一種情況也可以'som.most_common(3)' – Copperfield

0

這工作。

import operator 
data = {'L': 233, 'T': 208, 'I': 169, 'G': 167, 'V': 161, 'N': 155, 'R': 151, 'S': 149, 'K': 148, 'E': 146, 'A': 144, 'Q': 131, 'P': 97, 'D': 92, 'W': 92, 'Y': 85, 'C': 80, 'F': 78, 'M': 52, 'H': 44} 
sorted_data = list(sorted(data.items(), key=operator.itemgetter(1))) 
total_sum = sum(data.values()) 

# Print 3 highest 

print sorted_data[0], sorted_data[0][1]*100/float(total_sum) 
print sorted_data[1], sorted_data[1][1]*100/float(total_sum) 
print sorted_data[2], sorted_data[2][1]*100/float(total_sum) 

# Print 3 lowest 
print sorted_data[-1], sorted_data[-1][1]*100/float(total_sum) 
print sorted_data[-2], sorted_data[-2][1]*100/float(total_sum) 
print sorted_data[-3], sorted_data[-3][1]*100/float(total_sum)