python - 包含编号和名称排序的列表
问题描述
所以这个程序存储了一个名称和分数,然后将它存储在一个tet文档中,并将其排序到前5名的排行榜中,分数后跟名称。该文件写为 score,name,score,name... 但是在打印最终排序列表时,它将分数排序为字符串而不是整数 - 例如。98 97 87774 384 111 10000000
并不是10000000 87774 384 111 98 97
#importing os
import os
#checkingn if the file is empty
if os.stat("scores.txt").st_size == 0:
#if it is, setting up 5 blank scores to correct the ',' start and to
make the leaderboard more presentable
f = open('scores.txt','w')
f.write('0,Empty,0,Empty,0,Empty,0,Empty,0,Empty')
#input of new score and name
score = input('score: ')
name = input('Name: ')
#storing it
f = open('scores.txt','a+')
f.write(',')
f.write(score)
f.write(',')
f.write(name)
f.close()
#reading the file with , as a split so forming a list
f = open('scores.txt','r')
data = f.readline()
# Get and strip all data from the input string.
numdata = [value.strip() for value in data.split(',') if value is not '']
# Create pair from each name/score
data = list(zip(numdata[0::2], numdata[1::2]))
# Sort by score
leaderboard = sorted(data, key =lambda x: x[0], reverse=True)
print(leaderboard)
f.close()
如果有人知道我如何解决这个问题,将不胜感激
解决方案
您也可以通过这种方式应用 int 强制转换:
data.sort(key=int, reverse=True)
dara[:5].sort(key=int, reverse=True) # for first five
其中 data 是一个字符串数组。
请注意,排序已经到位,因此您不会在内存中创建另一个列表。
推荐阅读
- node.js - 如何使用 AWS 开发工具包 SES 发送附件
- python - 在 VS Code 中调试 Python Docker
- c - 如何处理 C 中超出时间限制的错误?
- css - 实现访问具有相同标题的电影的下拉菜单。反应,Axios,MovieDB API
- python - 将命令行参数从父节点 js 传递给子进程
- visual-studio-code - 无论如何要在 vscode keybindings.json 中执行多个命令吗?
- python - 检测图像上的裂缝_使用scikit-image标签修改图像
- excel - Excel。当我们比较具有相同索引的两列时,如何找到相同的最大值?
- python - xgboost如何复制模型
- java - 从富文本中提取base64字符串并将它们收集到一个数组中