python - 排序txt文件以创建排行榜
问题描述
每次有人在游戏中失败时,我都会尝试创建一个 txt 文件(以保存他们的分数)
我成功了,我现在有一个我想要排序的数字列表,最大的在前。然后每次刷新时我都会使用前 5 行。
我的 txt 文件(例如):
10
1
5
4
3
2
我想要的是:
10
5
4
3
2
1
谢谢
#Saving the score
Scorefile = open('Scoreboard.txt','a')
Scorefile.write(str(score))
Scorefile.write('\n')
Scorefile.close()
#Sorting the file
Scorefile = open('Scoreboard.txt','a')
解决方案
你可以这样做:
file = open("Scoreboard.txt","r")
lines = list(file) #create a list of strings
file.close() #don't forget to close our files when we're done. It's good practice.
modified_lines = [] #empty list to put our modified lines in (extracted number, original line)
for line in lines: #iterate over each line
if line.strip(): #if there's anything there after we strip away whitespace
score = line.split(' ')[0] #split our text on every space and take the first item
score = int(score) #convert the string of our score into a number
modified_lines.append([score, line]) #add our modified line to modified_lines
#sort our list that now has the thing we want to sort based on is first
sorted_modified_lines = sorted(modified_lines, reverse = True)
#take only the string (not the number we added before) and print it without the trailing newline.
for line in sorted_modified_lines:
print(line[1].strip())
输出:
10
5
4
3
2
1
推荐阅读
- windows - 从 Windows 7 通过 USB 连接到 Orbbec Persee 时出现问题
- java - JavaFX - 如何在可编辑的 TableView 中检查用户输入
- crm - Odoo vs 自制 cakephp 开发
- javascript - 创建自定义搜索管道以动态过滤结果后,我仍然失败:解析错误:找不到管道“过滤器”
- c++ - 每个线程完成后停止 io_service
- mysql - Spring Boot BCryptPasswordEncoder 编码密码看起来不像 BCrypt
- python - 如何组合 Python 32 位和 64 位模块
- python - 使用 POST 将 zlib 压缩数据发送到服务器
- java - Android Studio Java ANR 内存泄漏
- google-sheets - 索引匹配查找具有多个搜索条件的最接近的值