从.txt文件中找到最高得分的球员

2024-06-10 08:56:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个格式如下的文本文件-
星际玩家,1,19
月亮,3,12
鱼,4,8
星际玩家,3,9
埃莉,2,19
-还有50多条线等等。 第一列是球员姓名,第二列是级别号(1-5),第三列是分数。 我想找到总得分最大的球员-所以他们每个级别的得分加在一起。但我不确定每个玩家都是随机出现的。 到目前为止我的代码是-

    def OptionC():
        PS4=open("PlayerScores.txt","r").read()
        for line in PS4:
            lines=line.split(",")
            player=lines[0]
            level=lines[1]
            score=lines[2] 
        player1=0
        score=0
        print("The overall top scorer is",player1,"with a score of",score)

谢谢-请帮忙!!!在


Tags: 代码格式line玩家级别分数ps4score
3条回答

为什么不创建一个类?这使得管理球员档案变得非常容易。在

class Player:
    def __init__(self, name, level, score):
        # initialize the arguments of the class, converting level and score in integer
        self.name = name
        self.level = int(level)
        self.score = int(score)
# create a list where all the Player objects will be saved
player_list = []
for line in open("PlayerScores.txt", "r").read().split("\n"):
    value = line.split(",")
    player = Player(value[0], value[1], value[2])
    player_list.append(player)



def OptionC():
    # sort player_list by the score
    player_list.sort(key=lambda x: x.score)
    print("The overall top scorer is", player_list[-1].name, "with a score of", player_list[-1].score)

OptionC()

我假设水平与分数无关。在

你可以为玩家和他们的分数创建列表,并不断更新,即使有重复。最后找到最大值并打印出来。在

  def OptionC():
        PS4=open("PlayerScores.txt","r").read()
        top_player = 0
        top_score = 0
        player_list = []
        score_list = []
        for line in PS4:
            lines=line.split(",")
            player=lines[0]
            level=lines[1]
            score=lines[2] 

            #Check if the player is already in the list, if so increment the score, else create new element in the list
            if player in player_list:
                score_list[player_list.index(player)] = score_list[player_list.index(player)] + score
            else:
                player_list.append(player)
                score_list.append(score)

        top_score = max(score_list)
        top_player = player_list[score_list.index(top_score)]


        print("The overall top scorer is",top_player,"with a score of",top_score)

您可以在dictionary中保留与每个玩家相关联的分数,并将每个级别的分数添加到他们的总分中:

from collections import defaultdict

scores = defaultdict(lambda: 0)
with open(r"PlayerScores.txt", "r") as fh:
    for line in fh.readlines():
        player, _, score = line.split(',')
        scores[player] += int(score)

max_score = 0
for player, score in scores.items():
    if score > max_score:
        best_player = player
        max_score = score

print("Highest score is {player}: {score}".format(player=best_player, score=max_score))

相关问题 更多 >