-2
from heapq import nlargest

with open("winnernum.txt", "r") as f:
   numbers = [float(line.rstrip()) for line in f.readlines()]
   largest = nlargest(5, numbers)    
print(largest)

我已经测试了这段代码,如果每个数字旁边没有字符串,它就可以工作,因为我假设你不能将字符串转换为浮点数。该字符串在那里,因为每个高分旁边都有一个用户名。该程序应打印获胜者的姓名和得分最高的前 5 名玩家的得分。

4

2 回答 2

0

如果输入看起来像注释中描述的那样运行示例:

from heapq import nlargest

test_str = """ ['katy'] 30
['max'] 45
['A'] 31
['B'] 4
['D'] 1
['C'] 15
['E'] 333"""

numbers = [float(line.rstrip().split("]")[1]) for line in test_str.split("\n")]
largest = nlargest(5, numbers)
print(largest)

在你的情况下,你会这样做:

from heapq import nlargest

with open("winnernum.txt", "r") as f:
   numbers = [float(line.rstrip().split("]")[1]) for line in f.readlines()]
   largest = nlargest(5, numbers)    
print(largest)

编辑

避免空行或没有“]”的行

numbers = []
with open("winnernum.txt", "r") as f:
    for line in f.readlines():
        split = line.rstrip().split("]")
        if len(split) > 1:
            numbers.append(float(split[1]))
于 2019-12-27T18:44:37.687 回答
0

如果 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
于 2019-12-27T18:50:42.837 回答