【问题标题】:Getting index error in a Python `for` loop在 Python `for` 循环中获取索引错误
【发布时间】:2017-08-13 18:36:16
【问题描述】:

目标:将一个空的 ASCII 网格变成一个井字棋盘。 空的时候应该是这样的:

        |        |     
        |        |    
    ____|________|____
        |        |    
        |        |    
    ____|________|____
        |        |    
        |        |    
        |        |   

错误:

def myformat(moves, line):
# there's got to be a better way to do this
    if line in [1, 4, 7]:
        if moves[line] == 'x':
            return "\  /"
        elif moves[line] == 'o':
            return " oo "
        elif moves[line] == 'none':
            return "    "
    elif line in [2, 5, 8]:
        if moves[line] == x:
            return " xx "
        elif moves[line] == o:
            return "o  o"
        elif moves[line] == "none":
            return "    "
    elif line in [3, 6]:
        if moves[line] == x:
            return "/__\b"
        elif moves[line] == o:
            return "o__o"
        elif moves[line] == "none":
            return "____"
    elif line == 9:
        if moves[line] == x:
            return "/__\b"
        elif moves[line] == o:
            return "o__o"
        elif moves[line] == "none":
            return "    "        
    else:
        print("Fatal error.")
>>> moves = ['none']*9
>>> moves
['none', 'none', 'none', 'none', 'none', 'none', 'none', 'none', 'none']
>>> for line in range(1, 10):
   print("{}|{}|{}".format((myformat(moves, line))))

Traceback (most recent call last):
  File "<pyshell#24>", line 2, in <module>
    print("{}|{}|{}".format((myformat(moves, line))))
IndexError: tuple index out of range

full code因为上次有人生气我只发了一部分

我不明白为什么要提到元组。我看到的唯一一个是 range(1, 10) 函数,因为它是一个 for 循环,所以不应该出现索引错误。感谢所有 cmets 和批评。提前致谢。

【问题讨论】:

  • myformat 应该返回一个 3-len 元组来馈送format,但它只返回一个字符串。您希望格式可以猜到什么来填充其他字段?也许试试print("{0}|{0}|{0}"
  • Python 与大多数编程语言一样,从“0”开始计算索引,而不是从“1”开始计算 - “moves”中的最后一个索引是“8”,而不是“9”。
  • @Jean-FrançoisFabre 你说的很对。我在每个变量上写了return,当我打算写a='. . . ', b = ' . . . ', c=' . . . ' return a,b,c.之类的东西时,我会改变它,看看它是否能解决问题。
  • 很高兴能提供帮助。

标签: python python-3.x for-loop tuples indexoutofboundsexception


【解决方案1】:

在您的示例中,line = 1 myformat() 将返回一个包含 5 个空格的字符串..

让我们试试吧

>>> ret_val = '     '
>>> '{} | {} | {}'.format(ret_val)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

@Jean-François Fabre,已经解释过该格式需要 3 个值。
由于只有 1 个值字符串格式无法找到缺失值。
您需要通过提供索引来告诉格式它应该放在哪里。

>>> ret_val = '     '
>>> '{0} | {0} | {0}'.format(ret_val)
'      |       |      '

【讨论】:

    【解决方案2】:

    您的代码存在三个问题。

    首先是您的调用代码期望获得三个值,但您只从函数中返回一个值。

    第二个问题是,在函数中,您使用来自调用代码中的range(1, 10) 的值来索引moves。由于排除了rangestop 参数,因此最大值为9。这超出了moves(有九个值)的范围。 Python 索引从零开始,因此您可能需要range(0, 9) 或只是range(9)(或者您需要在获取每个索引之前从值中减去一个)。

    第三个问题是,您似乎在函数中将line 用于两个不同的目的。您正在使用它来索引板上的方格数组(通过moves 列表)。您还可以使用它对输出中的水平文本行进行编号。它们不是一回事,所以如果你继续交替使用它们,你会得到奇怪的结果。

    我不确定计算所需值的最佳方法是什么。如果您坚持迭代输出的行并希望您的函数返回三个值(对于行交叉的三个正方形),您需要从range(9) 传入一个line 值,然后用@ 索引987654333@ 加上来自range(3) 的值(这会将您引导到三个不同的方格)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 2020-09-07
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多