2017-02-19 56 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()