【问题标题】:Why am I getting a "String indices must be integers" error when I am indicing a dictionary?为什么我在索引字典时收到“字符串索引必须是整数”错误?
【发布时间】:2021-06-15 03:05:44
【问题描述】:

我正在尝试编写 python 控制台游戏框架。我是如何设计它的,有一个名为 game_state 的字典,它由传递给循环函数的函数更新。在循环的一次迭代之后,它给出了错误“字符串索引必须是整数”。堆栈跟踪显示错误发生在if game_state["running"] == false 行。打印出 game_state 时,它​​似乎是一个空字符串。为什么会发生这种情况,我可以做些什么来解决它?

def run_loop(calculate, draw, initial_state):
  fd = sys.stdin.fileno()
  old_settings = termios.tcgetattr(fd)
  tty.setraw(sys.stdin)
  game_state = initial_state
  with raw(sys.stdin):
    with nonblocking(sys.stdin):
      try:
        while True:
            try:
                c = sys.stdin.read(1)
                game_state = calculate(c, game_state)
                print_map(draw(game_state))
                if game_state["running"] == False:
                  break
            except IOError:
                print('not ready')
          
            time.sleep(.1)
      finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
  
def game(state, press):
  mut_state = state
  if press == "q":
    mut_state["running"] = False
  return mut_state
def display(game_state):
  return [["Yay!"]]
run_loop(game, display, {"running": True})

【问题讨论】:

  • calculate 必须返回一个字符串而不是您期望的字典...
  • game_state 显然是执行代码时的字符串。您是否尝试过打印或使用isinstance() 来验证您的期望?请注意:minimal reproducible example 应该有足够的细节让我们重现问题,包括calculate 和/或game_state
  • 我正在尝试,但它什么也没打印出来。这可能表明它是一个空字符串。
  • @G.Anderson 这些被传递到函数中。它包括那些。
  • 连接它表明它实际上是一个空字符串。

标签: python functional-programming console anonymous-function


【解决方案1】:

答案就在我面前。我首先传入了输入,这意味着空输入正在覆盖游戏状态。应该是calculate(game_state, c)

【讨论】:

    猜你喜欢
    • 2019-11-26
    • 1970-01-01
    • 2011-08-29
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多