2017-02-19 68 views
-3

我喜欢格式化这 -
Starplayer一个文本文件中得分最高的球员,1.19
月亮,3,12
鱼,4,8-
Starplayer,3,9-
艾莉,2,19
- 约50多行,等等。 第一列是玩家名字,第二列是等级号码(从1-5),第三列是得分。 我想找到总分最高的玩家 - 所以他们的每个级别的分数加在一起。但我不确定每个玩家都会随机出现多次。 这是我的代码,因此远寻找从.txt文件

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) 

谢谢 - 请帮助!

+0

不想给你复制/粘贴的答案,但:在所有的线环和比分比较之前记得最高分。如果它更高,则将其设置为最高分。在循环结束时,您将获得最高分。 – Carpetsmoker

+0

@Carpetsmoker这可以工作,但我需要将每个级别的每个球员得分加在一起。因此,例如,Starplayer的得分= 9 + 19,所以我想这是总共 –

+0

我投票结束这个问题作为题外话,因为SO不是一个编程服务。 –

回答

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