所以这个程序存储了一个名字和分数,然后将它存储在一个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()
如果有人知道我如何解决这个问题,我将不胜感激
要检索前5名的分数,不需要对整个分数列表进行排序。您可以使用^{} 跟踪并输出到最上面的n分数。你知道吗
当然,主要的问题是需要将字符串转换为整数进行比较。你知道吗
更好的是,您可以首先将输入数据转换为整数。然后,您就不再需要将
str
转换为int
作为排序过程的一部分。比如:也可以通过以下方式应用int cast:
其中数据是字符串数组。你知道吗
请注意,排序已经就绪,因此不会在内存中创建另一个列表。你知道吗
您可以使用键函数中的
int()
构造函数将分数转换为整数,以便对分数进行数字排序:如果只需要前5名,则还应将结果列表切片:
相关问题 更多 >
编程相关推荐