首页 > 解决方案 > 包含编号和名称排序的列表

问题描述

所以这个程序存储了一个名称和分数,然后将它存储在一个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()

如果有人知道我如何解决这个问题,将不胜感激

标签: pythonstringpython-3.xsortingpython-3.4

解决方案


您也可以通过这种方式应用 int 强制转换:

data.sort(key=int, reverse=True)

dara[:5].sort(key=int, reverse=True) # for first five

其中 data 是一个字符串数组。

请注意,排序已经到位,因此您不会在内存中创建另一个列表。


推荐阅读