【问题标题】:How do I print 1st place, 2nd place, etc. up to 5th place?如何打印第 1 名、第 2 名等直到第 5 名?
【发布时间】: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


【解决方案1】:

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

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]))

【讨论】:

    【解决方案2】:

    您可以简单地枚举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要转换为第一/第二/第三

    【讨论】:

    • 谢谢,这会打印 1 - example - 15。你可以让它打印 1st Place = example - 15?
    • @Adam - 这就是问题中的链接提供的帮助
    • 我无法使用链接,因为我的 python (python 3.3.4) 没有模块变形,这是链接建议使用的。
    • @Adam - 这个问题有多个答案,我想其中一个选项是合适的
    猜你喜欢
    • 2016-09-22
    • 2014-12-02
    • 2014-10-31
    • 2021-08-26
    • 1970-01-01
    • 2017-03-24
    • 2017-07-07
    • 2018-06-28
    • 2013-10-21
    相关资源
    最近更新 更多