简体   繁体   English

根据搜索追加更新Python列表

[英]Updating a Python list based on a search append

I am trying to create a very basic scoreboard system. 我正在尝试创建一个非常基本的计分板系统。 Scores to be read into a list from a file. 分数将从文件中读取到列表中。 If name exists the list to be updated with further scores (append). 如果名称存在,则将使用进一步的分数更新该列表(追加)。 New line to be created if name does not exist. 如果名称不存在,则创建新行。 I think its the append new score to list that's not working. 我认为将新分数添加到列表中不起作用。 Any help appreciated - learning. 任何帮助表示赞赏-学习。

message=""

#ask for name and score
name = input("Please enter the name you wish to add")
score = input("Please enter the high score")

#open the highscores line and read in all the lines to a list called ScoresList.
#  Then close the file.
scoresFile = open("highscores.txt","r")
ScoresList = scoresFile.readlines()
scoresFile.close()

#for each line in the ScoresList list
for i in range(0, len(ScoresList) ):

    #check to see if the name is in the line
    if name in ScoresList[i]:

        #append new score to list
        tempscore= ScoresList[i]
        ScoresList[i]=tempscore.append(score)
        message="Updated"

        #write the scores back to the file. Overwrite with the new list
        scoresFile = open("highscores.txt","w")
        for line in ScoresList:
            scoresFile.write(line + "\n")
        scoresFile.close()

    else:
       message = "Not updated"

if message=="":
        scoresFile = open("highscores.txt","a")
        scoresFile.write(name + str(score)+"\n")
        scoresFile.close()

ScoresList[i]=tempscore.append(score) makes ScoresList[i] equal to None as append is an in place method. ScoresList[i]=tempscore.append(score)使ScoresList[i]等于None因为append是一个就地方法。 So you are storing all None's in your ScoresList . 因此,您将所有None's存储在ScoresList

If you want to add a score to the name: 如果要在名称中添加分数:

name = input("Enter your name").rstrip() # make "foo" == "foo "
score = input("Enter your score")
with open("highscores.txt","a+") as f: # a+ will allow us to read and will also create the file if it does not exist
    scores_list = f.readlines()
     # if scores_list is empty this is our first run
    if not scores_list:
        f.write("{} {}\n".format(name, score))
    else:
        # else check for name and update score
        new_names = []
        for ind, line in enumerate(scores_list):
            # if name exists update name and score
            if name in line.split():
                scores_list[ind] = "{} {}\n".format(name, score)
                break # break so we don't add existing name to new names
        else:
            # else store new name and score
            new_names.append("{} {}\n".format(name, score))


        # all scores updated so open and overwrite
        with open("highscores.txt","w") as scores_file:
             scores_file.writelines(scores_list + new_names)

You also you already have all the scores in a list so open the file just once outside the loop when ScoresList is updated and overwrite instead of repeatedly opening each time. 您还已经将所有分数保存在列表中,因此在ScoresList更新并覆盖时,只需在循环外打开文件一次即可,而不是每次都重复打开。

If you want to add new scores instead of overwriting the score add score to the line instead of the name: 如果要添加新分数而不是覆盖分数,请将分数添加到行中而不是名称:

scores_list[ind] = "{} {}\n".format(line.rstrip(), score)

If you want to separate by commas and append each new score to exisiting names: 如果要用逗号分隔并将每个新分数添加到现有名称后:

with open("highscores.txt","a+") as f: # a+ will allow us to read and will also create the file if it does not exist
    scores_list = f.readlines()
     # if scores_list is empty this is our first run
    if not scores_list:
        f.write("{},{}\n".format(name, score))
    else:
        # else check for name and update score
        new_names = []
        for ind, line in enumerate(scores_list):
            # if name exists update name and score
            if name.rstrip() in line.split(","):
                scores_list[ind] = "{},{}\n".format(line.rstrip(), score)
                break # break so we don't add existing name to new names
        else:
            # else store new name and score
            new_names.append("{},{}\n".format(name, score))


        # all scores updated so open and overwrite
        with open("highscores.txt","w") as scores_file:
             scores_file.writelines(scores_list + new_names)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM