如何从Python字典中获取项目

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

我需要在哪里使用它以及如何使用?因为它在我现有的代码中无法工作。 - Ruben Oldenkamp
2个回答

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
太好了,这正是我所需要的。谢谢。 - Ruben Oldenkamp
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接