-2

I have a program that reads the top 5 (or all scores and usernames if there are less than 5 people on the leaderboard of a .csv file, called leaderboard2.csv.

However, in the python shell it says this:

Here is the Top 5 leaderboard:
Username - Score

123 - 74
example - 45
ok - 36
sample - 36
testing - 30

I would like to say 1st place, or 2nd place, so on next to each of the lines above in the shell. E.g. 2nd Place = example - 45.

How do I display it like above (When I do it, it is completely wrong as it displays everyone in the leaderboard next to "1st place = ")

Im using python 3.3.4 by the way.

Thanks in advance, here is my code below:

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))
Joe
  • 21
  • 6

2 Answers2

0

You could simply enumerate the most_common.

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

This of course, will just display the position (1,2,3,4,5), there are libraries and options available to convert to first/second/third

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • thanks, this prints 1 - example - 15. Can you make it print 1st Place = example - 15? – Joe Jan 05 '20 at 21:39
  • @Adam - That is what the link in the question provides assistance with – Sayse Jan 05 '20 at 21:40
  • I can't use the link because my python (python 3.3.4) doesnt have the module inflect, which is what the link suggests to use. – Joe Jan 05 '20 at 21:42
  • @Adam - There are multiple answers on that question, I'd imagine one of the options would be suitable – Sayse Jan 05 '20 at 21:43
0

So this may not be the most elegant of solutions but you could enumerate the list and use that and print out the correct place

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]))
Violenity
  • 16
  • 2