如果 test.txt 是
green 12
blue 13
red 14
yellow 15
hello 16
green1 122
blue1 132
red1 142
yellow1 152
hello1 162
green2 121
blue2 131
red2 141
yellow2 151
hello2 161
代码:
from heapq import nlargest
with open("test.txt",'r')as f:
c={}
for l in f:
c[l.split("]")[0]]=(float(l.split("]")[1]))
largest=nlargest(5,list(c.values()))
print(c)
print(largest)
for x in largest:
for i in c:
if c[i] == x:
print(i[1:],x)
输出:
{'green': 12.0, 'blue': 13.0, 'red': 14.0, 'yellow': 15.0, 'hello': 16.0, 'green1': 122.0, 'blue1': 132.0, 'red1': 142.0, 'yellow1': 152.0, 'hello1': 162.0, 'green2': 121.0, 'blue2': 131.0, 'red2': 141.0, 'yellow2': 151.0, 'hello2': 161.0}
[162.0, 161.0, 152.0, 151.0, 142.0]
hello1 162
hello2 161
yellow1 152
yellow2 151
red1 142