[英]Sorting .txt file lines adds an incorrect line
所以问题是,当我运行排行榜代码时,它会正确输出一些排行榜,但随后添加了不正确的行。
我试过删除txt文件的内容,没有用。
def save():
global totalone,totaltwo,name1,name2,rounds
file=open("scores.txt","a")
if totalone < totaltwo:
#name2 V name1 | totaltwo
file.write(f"Scored {totaltwo} | Winner:{name2} V {name1} | played 0 H2H rounds\r")
elif totaltwo < totalone:
#name1 V name2 | totalone
file.write(f"Scored {totalone} | Winner:{name1} V {name2} | Played 0 H2H rounds\r")
else:
#name1 V name2 | Tied | rounds
if totalone < totaltwo:
file.write(f"Scored {totalone} | Winner:{name1} V {name2} | Tied | Played {rounds} H2H rounds\r")
elif totaltwo < totalone:
file.write(f"Scored {totaltwo} | Winner:{name2} V {name1} | Tied | Played {rounds} H2H rounds\r")
file.close()
def leaderboard():
file=open("scores.txt","r")
data=file.readlines()
data.sort(reverse=True)
x = 0
for i in range(len(data)):
print((data[i].strip()))
x += 1
if x == 5:
break
file.close()
结果显示了一个无序列表。
Scored 20 | Winner:John V Kennedy | Played 0 H2H rounds
Scored 40 | Winner:John V Kennedy | Played 0 H2H rounds
Scored 10 | Winner:John V Kennedy | Played 0 H2H rounds
Scored 80 | Winner:John V Kennedy | Played 0 H2H rounds
我希望它们像这样显示:
Scored 80 | Winner:John V Kennedy | Played 0 H2H rounds
Scored 40 | Winner:John V Kennedy | Played 0 H2H rounds
Scored 20 | Winner:John V Kennedy | Played 0 H2H rounds
Scored 10 | Winner:John V Kennedy | Played 0 H2H rounds
data=file.readlines()
data.sort(reverse=True)
这按字母顺序对行进行排序,所以
Scored 7…
Scored 5…
Scored 4…
是正确的”。
在格式化输出行之前,您需要根据数字分数( totalone
或totaltwo
变量)进行排序。
请参阅@mkrieger1 的解决方案以获得真正正确的解决方案(实际上是在格式化之前根据具体值进行排序)。
对于快速和肮脏的解决方案,只需将您的data.sort(...)
替换为:
data.sort(reverse=True, key=lambda line: int(line.split()[1]))
这样做是告诉排序使用第一个和第二个空格之间的值(恰好是分数),并将其转换为 int(因此排序是数字而不是字母)
澄清:
这是一个非常糟糕的做法,因为如果您更改行格式,它可能会中断(这与排行榜的排序方式无关,仅与显示有关)。
所以,再一次,就软件工程而言,这不是一个好的做法。 快速且有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.