简体   繁体   中英

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?

How can I create a list that I can add to at the end of the piece of code and that I can use and add more to the next time I run through the code?

So I'm doing my NEA for GCSE Computer Science and I need to creat this game and save the top 5 scores in an external file. My plan is to put all of scores from game into a list, then sort the list so that the scores are in descending order, then display the first 5 elements of the list in the external file. I can't create the list before I enter the score because it will be empty when I run the code again and I can't add anything to a list that I haven't made yet!

    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

Basically, I want a list that I can keep adding things to every time I run through the code. How do I do this?

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

Save the scores in a file, and read the file when you start up. If the file doesn't exist yet, use an empty list.

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)

you need to save the data in a file somewhere. You can use pickle as stated in this answer :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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