如何打印第 1 名、第 2 名等直到第 5 名?

How do I print 1st place, 2nd place, etc. up to 5th place?

我有一个程序可以读取前 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

我想说第 1 名或第 2 名,依此类推 shell 上面每一行的旁边。例如。第二名 = 示例 - 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))

您可以简单地枚举 most_common

for i, common in enumerate(scores.most_common(5), 1):
    print(i, common[0] + " -", common[1])

这个当然只是显示位置(1,2,3,4,5),还有libraries and options available转换成first/second/third

所以这可能不是最优雅的解决方案,但您可以枚举列表并使用它并打印出正确的位置

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("")
place = 1
for i, v in enumerate(scores.most_common(5)):
  if i == 0:
    print("1st")
  elif i == 1:
    print("2nd")
  print(str(v[0]) + " - " + str(v[1]))