python - 如何将序数添加到文本文件中每一行的开头
问题描述
我有一个存储在文件中的游戏排行榜。文件的格式是这样的:
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
我查看了其他显示如何显示序数的帖子,但我仍然不知道如何执行此操作。
解决方案
像这样的东西...
def ordinal_string(i):
if i >= 10 and i <= 20:
suffix = 'th'
else:
il = i % 10
if il == 1:
suffix = 'st'
elif il == 2:
suffix = 'nd'
elif il == 3:
suffix = 'rd'
else:
suffix = 'th'
return str(i) + suffix + '. '
然后:
for i, line in enumerate(sorted_modified_lines): print(ordinal_string(i+1) + line[1].strip()+"\n")
推荐阅读
- angular - IONIC - HTTP Post 请求不起作用,可能是标头问题
- java - Kotlin:就地保留、替换或删除每个地图条目
- android - Android混淆不会更改包名称
- excel - 在 EXCEL 中创建运行状态跟踪器
- c - 从 C 向 GenServer 发送消息
- javascript - 如何在 JavaScript 中将数据提取到对象中?
- laravel - 有没有办法解决在 container.php Laravel 中找不到的类?
- javascript - 如何解决“无效元素类型”错误?
- python - 将光标聚焦到输入值的末尾(CreateView、ModelForm)
- java - 从控制器重定向到视图时,Thymeleaf 验证错误消息被刷新(丢失)