【问题标题】:python pickle IndexError: tuple index out of rangepython pickle IndexError:元组索引超出范围
【发布时间】:2017-12-27 13:09:02
【问题描述】:

您好,我正在做一个 python 文本冒险,我有一个保存功能可以保存所有主要变量库存、位置和黄金。然后我又添加了 2 个变量,但它不起作用。 提前致谢。

这是我的工作代码。

def do_save(self, arg):
    saveGame = open('savegame.txt', 'wb')
    saveValues = (inventory, gold, location)
    pickle.dump(saveValues, saveGame)
    saveGame.close()

def do_load(self, arg):
    global inventory
    global gold
    global location
    global equiped
    global health
    loadGame = open('savegame.txt', 'rb')
    loadValues = pickle.load(loadGame)
    inventory = loadValues[0]
    gold = loadValues[1]
    location = loadValues[2]
    loadGame.close()

这是不工作的代码

def do_save(self, arg):
    saveGame = open('savegame.txt', 'wb')
    saveValues = (inventory, gold, location, equiped, health)
    pickle.dump(saveValues, saveGame)
    saveGame.close()

def do_load(self, arg):
    global inventory
    global gold
    global location
    global equiped
    global health
    loadGame = open('savegame.txt', 'rb')
    loadValues = pickle.load(loadGame)
    inventory = loadValues[0]
    gold = loadValues[1]
    location = loadValues[2]
    equiped = loadValues[3]
    health = loadValues[4]
    loadGame.close()

我得到的错误信息是 IndexError: tuple index out of range

【问题讨论】:

  • 跟踪的确切错误是什么? loadValues 可能没有你想象的那么多元素。您是否验证了其中包含的内容?
  • 2 sn-ps 乍一看似乎是正确的。你确定你没有混合来自第一个sn-p的do_save和来自第二个sn-p的do_load吗?在使用它之前尝试打印loadValues。另外,arg 好像没用过。

标签: python python-2.7 pickle


【解决方案1】:

我想出了一个解决方案,但这可能不是最有效的方法,这里是代码

def do_save(self, arg):
    saveGame = open('savegame.txt', 'wb')
    saveValues = (inventory, gold, location, equiped, health)
    saveValues1 = (equiped, health)
    pickle.dump(saveValues, saveGame)
    pickle.dump(saveValues1, saveGame)
    saveGame.close()

def do_load(self, arg):
    global inventory
    global gold
    global location
    global equiped
    global health
    loadGame = open('savegame.txt', 'rb')
    loadValues = pickle.load(loadGame)
    inventory = loadValues[0]
    gold = loadValues[1]
    location = loadValues[2]
    equiped = loadValues[3]
    health = loadValues[4]
    loadGame.close()
    displayLocation(location)

【讨论】:

    猜你喜欢
    • 2013-12-16
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 2018-11-16
    • 2017-07-12
    相关资源
    最近更新 更多