从.txt文件中找到得分最高的玩家

时间:2017-02-19 17:08:49

标签: python python-3.x

我有一个像这样格式的文本文件 Starplayer,1,19
月亮,3,12
鱼,4,8-
Starplayer,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)

谢谢 - 请帮助!!!

3 个答案:

答案 0 :(得分:0)

您可以将每个玩家的分数保持在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))

答案 1 :(得分:0)

为什么不创建一个类?这使得管理玩家资料变得更加容易。

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()

答案 2 :(得分:-1)

我假设等级与分数没有任何关系。

您可以为玩家及其分数创建列表,并且即使有重复项也会继续更新。最后找到最大值并打印。

  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)