I have a programming challenge at school where i make a game and at the end, it prints the top five scores of all time. I have been able to get it to print the top five scores but I dont know how to make it print the score with the username along it. The code is:
with open("login.csv") as f:
print(" ")
print(" ")
print("Usernames and scores:")
reader=csv.reader(f)
scores=(row[-1] for row in reader)
topscore=sorted(scores, reverse=True)
top5=topscore[:5]
print(top5)
The output i get is:
Usernames and scores:
['82', '80', '66', '64', '62']
My desired output however is:
Usernames and scores:
Dylan, 82
f, 80
Farai, 66
Dylan, 64
Dylan, 62
Any help Dylan
I missed this out but the columns go name, password, score. Sorry for missing that out guys.
You can sort the rows together with a key function that allows the sorting to be based on the last column:
with open("login.csv") as f:
print(" ")
print(" ")
print("Usernames and scores:")
reader=csv.reader(f)
topscore=sorted(reader, key=lambda row: int(row[-1]), reverse=True)
top5=topscore[:5]
print('\n'.join(', '.join((username, score)) for username, _, score in top5))
It appears you're selecting only the score through the list comprehension. Assuming that the CSV is something like < username > , < score >, maybe the following will work?
with open("login.csv") as f:
print(" ")
print(" ")
print("Usernames and scores:")
reader=csv.reader(f)
scores=(row for row in reader)
topscore=sorted(scores, reverse=True)
for score in topscores:
print(score[0] +",\t" + score[1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.