繁体   English   中英

如何保存在一段代码中创建的列表,以便在再次使用同一代码时可以再次使用它?

[英]How can I save a list created in a piece of code so that I can use it again when I use the same code again?

如何创建一个列表,可以在代码末尾添加到该列表,并可以在下次运行代码时使用并添加更多列表?

所以我正在为GCSE计算机科学做NEA,我需要创建这个游戏并将前5个得分保存在一个外部文件中。 我的计划是将游戏中的所有得分都放入一个列表中,然后对列表进行排序,以便得分按降序排列,然后在外部文件中显示列表的前5个元素。 在输入分数之前,我无法创建列表,因为再次运行代码时它将为空,并且无法将任何内容添加到尚未创建的列表中!

    Top5=[]    
    Top5.append([name, score])
    #I can’t use this because it will wipe the list every time I use the code


    Top5.append([name, score])
    #I can’t use this because there is no list created to add to

基本上,我想要一个列表,可以在每次运行代码时不断添加内容。 我该怎么做呢?

由于您必须在外部文件中列出得分最高的得分手,因此只需创建一个外部文本文件并从该文件中读取/写入

将分数保存在文件中,并在启动时读取文件。 如果该文件尚不存在,请使用一个空列表。

import json

try:
    with open("highscores.json") as f:
        top5 = json.load(f)
except:
    top5 = []

# play game

if score > top5[-1]['score']:
    # Add new score to high scores
    top5.append({"player": name, "score": score})
    top5 = sorted(top5, key = lambda e: e['score'], reverse = True)[:5]

with open("highscores.json", "w") as f:
    json.dump(top5, f)

您需要将数据保存在某个文件中。 您可以按照以下答案使用泡菜:

import pickle

name = 'name'
score = 'score'
top5 = []
top5.append([name, score])

with open('filename.pickle', 'wb') as handle:
    pickle.dump(top5, handle, protocol=pickle.HIGHEST_PROTOCOL)

with open('filename.pickle', 'rb') as handle:
    b = pickle.load(handle)
    print(b) # b is your original object top5

暂无
暂无

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

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