Python Error: list indices must be integers or slices, not tuple

Python Error: list indices must be integers or slices, not tuple

def openMap(uArr, oArr, i):
    y = int(input("Row Number"))
    x = int(input("Column Number"))
    uArr[y,x] = oArr[y,x]
    printMap(uArr)
    if oArr[y,x] == "X":
        return 0
    else:
        return 1

uArr 指的是 user 数组,oArr 指的是 original 数组。

我收到这个错误:

list indices must be integers or slices, not a tuple

有人可以帮忙调试吗?

在普通的 Python 多维列表中,您不能像 uArr[y, x] 那样访问元素。而是使用 uArr[y][x].

也许你是说 if oArr[y][x] == "X":?您不能传递 2 个数字来为列表编制索引。

传递 [y,x] 意味着 oArr[(y,x)] 并且列表索引需要一个整数。 你应该这样做:

if oArr[y][x] == "X":

错误消息指出 Python 中的常见语法错误。

索引时出现语法错误

list indices must be integers or slices, not a tuple

这是由于在索引列表(或数组)时使用了错误的语法造成的。您用作索引的代码 x,y 被解释为像 (x,y).

这样的元组

正确的是 单个 整数,如 array[1]array[x] 或像 array[1:2] 的切片以获得第二到第三个元素.

参见文章 TypeError: list indices must be integers or slices, not str 中的解释。

任何多维数组或列表中的索引都必须添加在单独的括号中。因此 [x][y][z] 索引立方体或 3D 数组中的单个元素,而您的二维数组将只使用类似 [x][y].

的内容

急需修复

要修复它,只需将所有 [y,x] 替换为 [y][x]

def openMap(uArr, oArr, i):
    y = int(input("Row Number"))
    x = int(input("Column Number"))  # fixed a typo

    uArr[y][x] = oArr[y][x]
    printMap(uArr)
    
    if oArr[y][x] == "X":
        return 0
    else:
        return 1

额外提示:验证用户输入以避免越界错误

如果用户输入 -1999999999999 会怎样?您的数组或列表是否允许负索引或具有这么大的大小?

你应该先检查一下,然后要求输入正确的内容。

    last_row = len(oArr)-1  # last index because zero-based
    y = last_row + 1  # initially out-of-bounds to enter the loop
    while not 0 <= y <= last_row:
        y = int(input("Row Number ({}..{}): ".format(0, last_row)))
    
    last_col = len(oArr[0])-1  # suppose it's quadratic = all rows have same length
    x = last_col + 1  # initially out-of-bounds to enter the loop
    while not 0 <= x <= last_col:
        x = int(input("Column Number ({}..{}):".format(0, last_col)))

注意:从技术上讲,像 -1 这样的负索引将指向最后一个元素,-2 指向最后一个元素,依此类推。

另见相关问题:

  • Determine Whether Integer Is Between Two Other Integers?
  • Python - Input Validation