Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将第一名、第二名等打印到第五名?_Python_Python 3.x_Python 3.3 - Fatal编程技术网

Python 如何将第一名、第二名等打印到第五名?

Python 如何将第一名、第二名等打印到第五名?,python,python-3.x,python-3.3,Python,Python 3.x,Python 3.3,我有一个程序,可以读取前5名(或所有分数和用户名,如果.csv文件排行榜上的人数少于5人,则称为Leadboard2.csv) 但是,在python shell中,它表示: Here is the Top 5 leaderboard: Username - Score 123 - 74 example - 45 ok - 36 sample - 36 testing - 30 我想说第一名,或者第二名,依此类推,在shell中上面的每一行旁边。例如,第二名=示例-45 我如何像上面那样显示它

我有一个程序,可以读取前5名(或所有分数和用户名,如果.csv文件排行榜上的人数少于5人,则称为Leadboard2.csv)

但是,在python shell中,它表示:

Here is the Top 5 leaderboard:
Username - Score

123 - 74
example - 45
ok - 36
sample - 36
testing - 30
我想说第一名,或者第二名,依此类推,在shell中上面的每一行旁边。例如,第二名=示例-45

我如何像上面那样显示它(当我这样做时,它完全错了,因为它在排行榜“1st place=”旁边显示所有人)

顺便说一下,我正在使用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))

您可以简单地枚举最常见的

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

当然,这只会显示位置(1,2,3,4,5),需要转换为第一/第二/第三个位置,因此这可能不是最优雅的解决方案,但您可以列举列表并使用它打印出正确的位置

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

会列举出最常见的满足条件吗?你是在问如何将
1
变成
“1”
?@SethMMorton是的,使用下面提供的代码,这将打印1-example-15。您能让它打印1st Place=example-15吗?@Adam-这就是问题中的链接提供帮助的地方我不能使用链接,因为我的python(python 3.3.4)没有模块拐点,这是链接建议使用的。@Adam-这个问题有多个答案,我想其中一个选项是合适的