簡體   English   中英

如果我的文本文件在 Python 中有整數和字符串,我該如何排序

[英]How do I sort my text file if it has Integers and Strings in Python

我正在為我的課程代碼做一個高分系統,我設法在here的幫助下對我的數字進行了排序,但是現在我決定添加名稱,以便高分與一個人相關聯,它確實對它進行了排序,這是到目前為止我的代碼:

player1=input("input")
player1score=int(input("input"))


highscore = open("Scores.txt", "r")
whowon=("{0}-{1}".format(player1score,player1))
highscores = highscore.readlines()
highscore.close()
highscore = open("Scores.txt", "a")
highscore.write(whowon)
highscore.write("\n")
highscore.close()
highscore = open("Scores.txt", "r")
highscores = highscore.readlines()

highscores = [ x.rstrip() for x in highscores ]
highscores.sort(reverse=True, key=int)

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]
top=("{0}\n{1}\n{2}\n{3}\n{4}\n".format(top1, top2, top3, top4, top5))


highscore.close()

highscore=open("Scores.txt", "w")
highscore.write(top)
highscore.close()


文件輸出

68-Dylan
45-Snones
70-Pedro

有沒有辦法可以分離整數值,對它們進行排序,然后將它們分別放回一起? 我為此得到的錯誤代碼是

highscores.sort(reverse=True, key=int)
ValueError: invalid literal for int() with base 10: '68-Dylan'

假設這是您的輸入字符串。 您可以使用sorted ,它需要一個key參數來在排序之前轉換數據:

l = '''68-Dylan
45-Snones
70-Pedro'''.splitlines()

sorted(l, key=lambda x: int(x.split('-', 1)[0]))
# ['45-Snones', '68-Dylan', '70-Pedro']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM