You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按数值列排序CSV文件并输出Top 5高分玩家?

Fixing Your Leaderboard Top 5 High Score Issue

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:

  1. 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").
  2. Sort the list of players in descending order based on their score.
  3. 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=True ensures we prioritize the highest scores first.
  • Removed manual file.close(): When using a with statement 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:12:31