我有一个存储在文件中的游戏排行榜。文件格式如下:
bob has 46 points
fred has 0 points
leo has 27 points
我有这个代码来显示从升序到降序的分数:
if ens == "s":
print("\n"+"LeaderBoard: "+"\n")
f = open("scores.txt","r")
lines = list(f) #create a list of strings
f.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(' ')[2] #split our text on every space and take the third 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()+"\n")
输出:
bob has 46 points
leo has 27 points
fred has 0 points
我想要的是在分数前面显示序号,如下所示:
1st. bob has 46 points
2nd. leo has 27 points
3rd. fred has 0 points
我看过其他的文章,展示了如何显示序数,但我仍然不知道如何做到这一点。你知道吗
将最后一行替换为下面的两行,序号作为here的引用
我觉得你被否决了,因为看起来你没有那么努力,你也没有说你做了什么,但你还是来了:像这样的事情。。。你知道吗
然后:
相关问题 更多 >
编程相关推荐