因此,我尝试创建的基本概念是搜索.txt文件并找到游戏的最高得分者并将他所有级别的得分结合起来。更多信息: 我的.txt文件格式如下:
Username:level:Score
Starplayer:2:24
John:2:14
Starplayer:3:14
以上例如最高得分手将是Starplayer,得分为38分,因为它们都是得分。这是我到目前为止所得到的:
search = input("Enter the player name you want to search up for: ")
print("\nThe level scores for ",search," are:\nGame Level Score:")
searchfile = open("playerScores.txt", "r")
for line in searchfile:
if search in line: print("Level: ",(line.split(",")[1])," Score: ",(line.split(",")[2]))
searchfile.close()
以上在.txt文件中找到了一个特定播放器的名称并告诉你他们的分数。现在也许这可以与一些额外的代码相结合,以找到for循环中的所有分数,并且在找到最高分之前不停止。我不是100%自己如何做到这一点,所以我在这里寻求帮助。 如果您有任何建议,非常感谢您:)
答案 0 :(得分:3)
在这里使用词典要容易得多
players = {}
with open("playerScores.txt", "r") as searchfile:
searchfile.readline() # skip headers
for line in searchfile:
line = line.rstrip().split(":")
if line[0] in players:
players[line[0]] += int(line[2])
else:
players[line[0]] = int(line[2])
players = [[v,k] for k,v in players.items()]
players.sort(reverse=True)
# players is now in order of highest scoring players with it [score,name] for each element
使用字典的原因是它可以更容易地跟踪看到的玩家(因为你可以将名称作为字典中的键,并指向得分值)。
但是,如果你真的想要的话,你可以只使用列表来做到这一点。这只需要遍历我们的列表,直到我们找到合适的玩家来添加分数。它在功能上与上述相同,但速度较慢。
players = []
with open("playerScores.txt", "r") as searchfile:
searchfile.readline() # skip headers
for line in searchfile:
line = line.rstrip().split(":")
found = False
for i in range(len(players)):
if players[i][1] == line[0]:
players[i][0] += int(line[2])
found = True
if not found:
players.append([int(line[2]),line[0]])
players.sort(reverse=True)
这两个答案都会为您提供[[top-score, player], [second-score, player],...]
如评论中所述,如果您只对顶级玩家(而不是其他玩家)感兴趣,而不是排序,则可以使用max(players)
并返回顶部{ {1}}对。
答案 1 :(得分:2)
我也是python中词典的忠实粉丝。你循环遍历文件,将每个玩家添加到字典中(如果它还没有在那里)。如果它在那里你只需将已经存在的分数与你读过的分数结合起来。
score_dictionary = {}
with open('scorefile.txt') as handle:
for line in handle:
line = line.rstrip()
name = line.split(":")[0]
score = int(line.split(":")[2])
if name not in list(score_dictionary):
score_dictionary[name] = score
else:
score_dictionary[name] = score_dictionary[name] + score
values = list(score_dictionary.values())
keys = list(score_dictionary.keys())
print keys[values.index(max(values))], max(values)
在这种情况下,您应该重写您的分数文件,使其不再包含标题,它看起来像这样:
Starplayer:2:24
John:2:14
Starplayer:3:14
此脚本将提供以下输出:
Starplayer 38