I’m trying to create a leaderboard for a game, where after the game has been played, the python script accesses a CSV file (not ordered) and prints out the top 5 people with the highest score. Python seems to do this fine with single-digit numbers, but I can’t get it to work with 2 digit numbers. Here is the code:
import csv import operator sample = open('csv_sample2.txt', 'r') csv1 = csv.reader(sample,delimiter=',') sort = sorted(sample, key=operator.itemgetter(1)) for eachline in sort: print(eachline)
and here is the output: (I just used placeholder names for now)
['Matt Damon', ' 12'] ['Robin Williams', ' 14'] ['Billy Crystal', ' 15'] ['Minnie Driver', ' 17'] ['Peter Sellers', ' 6'] ['Robert De Niro', ' 8'] ['Stanley Kubrick', ' 9']
and here is the original leaderboard file:
Matt Damon, 12 Robert De Niro, 8 Billy Crystal, 15 Peter Sellers, 6 Stanley Kubrick, 9 Robin Williams, 14 Minnie Driver, 17
How do I get it to order the numbers properly?
Advertisement
Answer
I suggest simply reading the file with file.readlines() and then processing the finished results.
Input File:
Matt Damon, 12 Robert De Niro, 8 Billy Crystal, 15 Peter Sellers, 6 Stanley Kubrick, 9 Robin Williams, 14 Minnie Driver, 17
Code:
data = [] with open('your_file.txt', 'r') as f: scores = f.readlines() # data is a list of tuples with a string name as the # first value and a integer score as the second value data = [ ( s.strip().split(', ')[0], int(s.strip().split(', ')[1]) ) for s in scores ] sorted_data = sorted(data, key=lambda tup: tup[1], reverse=True) for name, score in sorted_data: print(f'{name} got a score of {score}') # Prints: # Minnie Driver got a score of 17 # Billy Crystal got a score of 15 # Robin Williams got a score of 14 # Matt Damon got a score of 12 # Stanley Kubrick got a score of 9 # Robert De Niro got a score of 8 # Peter Sellers got a score of 6
To print out only the first five scores from the ordered list sorted_data
, use a for x in range() loop:
for x in range(5): name, score = sorted_data[x] print(f'{name} got a score of {score}')
This for loop will run 5 times. It unpacks the name and score contained in the tuple stored at sorted_data x
, and then prints out that data.