gpt4 book ai didi

python - 包含编号和名称排序的列表

转载 作者:太空宇宙 更新时间:2023-11-03 21:39:32 27 4
gpt4 key购买 nike

因此,该程序存储名称和分数,然后将其存储在 tet 文档中,并将其排序到前 5 名排行榜中,分数后面跟着名称。该文件写为分数,名称,分数,名称...但是,当打印最终排序列表时,它将分数排序为字符串而不是整数 - 例如。 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() 构造函数将分数转换为整数,以便分数按数字排序:

leaderboard = sorted(data, key =lambda x: int(x[0]), reverse=True)

如果您只想要前 5 个,那么您还应该对结果列表进行切片:

leaderboard = sorted(data, key =lambda x: int(x[0]), reverse=True)[:5]

关于python - 包含编号和名称排序的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52985053/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com