【问题标题】:Why is my 2-d list holding a maximum of 2 items为什么我的二维列表最多包含 2 个项目
【发布时间】:2017-02-21 05:02:16
【问题描述】:

我使用 python 和 pygame 制作了一个游戏,我刚刚开始尝试通过节省时间和名称来做一些事情。但是,当列表中有 2 个项目时,第一个项目保存并且工作正常,但每次我完成游戏时第二个项目都会被覆盖。

try:
    openFile = open("times.txt", "rb")
    runTimes = pickle.load(openFile)
    runTimes.append([g.name, g.count])
    openFile.close()
except FileNotFoundError:
    runTimes = []
    runTimes.append([g.name, g.count])
    openFile = open("times.txt", "wb")
    pickle.dump(runTimes, openFile)
    openFile.close()

if len(runTimes) > 1:
    print(runTimes)

运行 1 = 没有任何反应

运行 2

[['Undefined', 7.5], ['Undefined', 8.3]]

运行 3

[['Undefined', 7.5], ['Undefined', 7.5]]

【问题讨论】:

  • 什么是g?它在哪里初始化?

标签: python python-3.x multidimensional-array pygame pickle


【解决方案1】:

try: 块成功更新您的文件时,您是否也忘记了pickle.dump?这可能就是你想要的:

try:
    openFile = open("times.txt", "rb")
    runTimes = pickle.load(openFile)
    openFile.close()
except FileNotFoundError:
    runTimes = []

runTimes.append([g.name, g.count])
openFile = open("times.txt", "wb")
pickle.dump(runTimes, openFile)
openFile.close()

if len(runTimes) > 1:
    print(runTimes)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多