如何按数值列排序CSV文件并输出Top 5高分玩家?
Hey there! The problem you're running into is that right now, you're just pulling the first 5 rows from your CSV file in the order they were written—you aren't sorting the entries by their score to get the highest values first. Let's fix that with a few simple changes to your code.
What's Wrong with the Current Approach?
Your code reads the CSV into score_list and uses islice to grab the first 5 rows, but those rows are in the order winners were added to the file, not sorted by their score. So you're getting the first 5 winners ever, not the top 5 highest scores.
How to Fix It
We need to:
- Convert the score values from strings to integers (since CSV reads all values as strings, and sorting strings would give incorrect results like "100" being treated as smaller than "99").
- Sort the list of players in descending order based on their score.
- Then take the top 5 entries from the sorted list.
Here's the updated version of your file reading/printing section (I kept your original code structure intact):
import csv from itertools import islice def main(): setup() print('Player 1 log in:') user1 = login() print('Player 2 log in: ') setup() user2 = login() print(user1, 'vs', user2) (player1, player1_win), (player2, player2_win) = game(user1, user2) if player1_win: winner = (user1, player1) else: winner = (user2, player2) print('Well done,', winner[0],' you won with ', winner[1], ' Points') with open('Leaderboard.csv', 'a', newline='') as file: wr = csv.writer(file) wr.writerow((winner)) # Updated leaderboard section with open('Leaderboard.csv', 'r', newline='') as file: score_list = list(csv.reader(file)) # Skip this line if your CSV has a header row (add score_list = score_list[1:] instead) # Sort by score (convert to int first) in descending order sorted_scores = sorted(score_list, key=lambda x: int(x[1]), reverse=True) print('\nThe top five players are: \n') for row in islice(sorted_scores, 5): print(*row) # Note: You don't need file.close() here—the `with` block handles closing automatically!
Key Changes Explained:
sorted(score_list, key=lambda x: int(x[1]), reverse=True): This sorts the list using the second element of each row (the player's score) converted to an integer.reverse=Trueensures we prioritize the highest scores first.- Removed manual
file.close(): When using awithstatement to open files, Python automatically closes the file once the block ends, so this line was redundant. - Header row note: If your CSV has a header (like "Username,Score"), add
score_list = score_list[1:]right after reading the list to skip the header during sorting.
Testing This
After making these changes, every time you run the program, the leaderboard will display the 5 players with the highest scores, regardless of when they were added to the CSV.
内容的提问来源于stack exchange,提问作者SpartanRJB

