我有以下字典:
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)
这很有效。
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)