gpt4 book ai didi

python - 如何保存过去的高分?

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:56 24 4
gpt4 key购买 nike

我目前有一个高分列表的代码:

scores = []
choice = None
while choice != "0":
print(
"""
High Scores
0 - Quit
1 - List Scores
2 - Add a Score
"""
)
choice = input("Choice: ")
print()
if choice == "0":
print("Goodbye")
elif choice == "1":
print("High Scores\n")
print("NAME\tSCORE")
for entry in scores:
score, name = entry
print(name, "\t", score)
elif choice == "2":
name = input("What is your name? ")
score = int(input("What score did you get? "))
entry = [score, name]
scores.append(entry)
scores.sort(reverse=True)
scores = scores[:10]
else:
print("Sorry, but", choice, "isn't a valid choice.")

谁能告诉我如何添加代码,以便下次使用该程序时保存高分

最佳答案

您最好的选择是 json module :

import json

def load_scores():
with open("scores.json") as infile:
return json.load(infile)

def save_scores(scores):
with open("scores.json", "w") as outfile:
json.dump(scores, outfile)

现在您可以调用 save_scores(scores) 来保存当前的高分列表,并执行 scores = load_scores() 从文件中取回它们。

关于python - 如何保存过去的高分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27212902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com