[英]How to sort a .txt file numerically
我无法按数字对.txt文件进行排序。 我已经附上了代码,并试图按分数对它进行排序,但我也无法将其从txt文件中将每个新分数打印到新行中。
def Highscore():
name = input("What is your name for the scoreboard?")
newhighscore =(name, highscore)
newline = ("\n")
HighscoreWrite = open ("highscore.txt", "a")
HighscoreWrite.write(highscore )
HighscoreWrite.write(name )
HighscoreWrite.write("\n")
HighscoreWrite.close()
HighscoreRead = open("highscore.txt", "r" )
ordered = sorted(HighscoreRead)
print (ordered)
print (HighscoreRead.read())
#print (newhighscore)
HighscoreRead.close()
retry = "Yes"
while retry == "Yes":
print ("Welcome to this quiz.\n")
score = 0
attempt = 0
while score < 10:
correct = Question()
if correct:
score += 1
attempt += 1
print ("Well done, You got it right")
else:
print ("Good try but maybe next time")
attempt += 1
highscore = score, ("/") ,attempt
highscore = str(highscore)
message = print ("You scored", (score), "out of ",(attempt))
Highscore();
retry = input("Would you like to try again? Yes/No")
为了对文件进行数字排序,您必须创建一个以行为参数并返回分数的数值的key(line)
函数。
假设highscore.txt是一个文本文件,其中每行以数字值开头,后跟一个空格,则key
功能可能是:
def key_func(line):
return int(line.lstrip().split(' ')[0])
然后,您可以使用ordered = sorted(HighscoreRead, key = key_func)
由于它是单行函数,因此您也可以使用lambda:
ordered = sorted(HighscoreRead, key= (lambda line: int(line.lstrip().split(' ')[0])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.