基于搜索追加更新Python列表

时间:2015-01-04 21:53:39

标签: python list append

我正在尝试创建一个非常基本的记分牌系统。分数从文件读入列表。如果名称存在,则要使用更多分数更新列表(追加)。如果name不存在,则创建新行。我认为它附加的新分数列表不起作用。任何帮助表示赞赏 - 学习。

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

1 个答案:

答案 0 :(得分:1)

ScoresList[i]=tempscore.append(score)使ScoresList[i]等于None,因为追加是一种就地方法。因此,您要将所有None's存储在ScoresList

如果您想为名称添加分数:

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)

您还可以在列表中获得所有分数,因此在更新ScoresList时只在循环外打开一次文件并覆盖而不是每次重复打开。

如果您想添加新分数而不是覆盖分数,请在该行中添加分数而不是名称:

scores_list[ind] = "{} {}\n".format(line.rstrip(), 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.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)