如何创建一个列表,可以在代码末尾添加到列表中,并且可以在下次运行代码时使用并添加更多列表?
所以我正在为GCSE计算机科学做NEA,我需要创建这个游戏并将前5个得分保存在一个外部文件中。我的计划是将游戏中的所有得分放入一个列表中,然后对列表进行排序,以便得分按降序排列,然后在外部文件中显示列表的前5个元素。 输入分数之前,我无法创建列表,因为再次运行代码时该列表将为空,并且无法向列表中添加尚未添加的任何内容!
var heroesRepository: HeroesRepository = mock()
基本上,我想要一个列表,可以在每次运行代码时不断添加内容。我该怎么做?
答案 0 :(得分:0)
由于您必须在外部文件中列出得分最高的得分手,因此只需创建一个外部文本文件并从该文件中读取/写入
答案 1 :(得分:0)
将分数保存在文件中,并在启动时读取文件。如果文件尚不存在,请使用一个空列表。
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)
答案 2 :(得分:0)
您需要将数据保存在文件中的某个位置。您可以按照以下answer中的说明使用泡菜:
<table>
<tbody class="files">
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<div class="files">
</div>
<table>
<tr>
<td>
<div class="files">
</div>
</td>
<td></td>
</tr>
</table>