【发布时间】:2020-01-05 21:17:38
【问题描述】:
我有一个程序可以读取前 5 名(或所有分数和用户名,如果 .csv 文件的排行榜上少于 5 人,称为 leaderboard2.csv。
但是,在 python shell 中它是这样写的:
Here is the Top 5 leaderboard:
Username - Score
123 - 74
example - 45
ok - 36
sample - 36
testing - 30
我想说第一名或第二名,等等在上面的每一行的外壳中。例如。第二名 = 示例 - 45。
我如何像上面那样显示它(当我这样做时,这是完全错误的,因为它会在排行榜中显示“第一名=”旁边的所有人)
顺便说一下,我使用的是 python 3.3.4。
提前致谢,下面是我的代码:
import csv
from collections import Counter
scores = Counter()
with open('leaderboard2.csv') as f:
for name,score in csv.reader(f):
# convert score into integer
score = int(score)
scores[name] = score
# list the top five
print("Here is the Top 5 leaderboard:")
print("Username - Score")
print("")
for name, score in scores.most_common(5):
print(name + " - " + str(score))
【问题讨论】:
-
enumerate-ing most_common 就够了吗? -
你是在问如何把
1变成"1st"? -
@SethMMorton 是的,使用下面提供的代码
标签: python python-3.x python-3.3