Numpy报”TypeError:list indices must be integers or slices,not tuple “的原因以及解决办法

  • Post category:Python

出现”TypeError:list indices must be integers or slices,not tuple”这个错误时,通常是因为在使用numpy时,尝试使用tuple类型的索引,而numpy数组是不支持tuple索引的,只支持整数或切片类型的索引。

以下是解决这个问题的完整攻略:

  1. 确认错误的代码所在位置以及错误提示中的行号和列号。

  2. 确认错误的代码中是否使用了tuple类型的索引。可以通过打印这些索引,如下示例:

import numpy as np
arr = np.array([[1, 2], [3, 4]])
idx = (0, 1)
print(arr[idx])

如果输出结果为”TypeError: list indices must be integers or slices, not tuple”,则说明使用了tuple类型的索引。

  1. 修改代码,使用整数或切片类型的索引。例如,将上述示例中的代码修改如下:

import numpy as np
arr = np.array([[1, 2], [3, 4]])
idx = [0, 1]
print(arr[idx])

或者:

import numpy as np
arr = np.array([[1, 2], [3, 4]])
idx1 = slice(None, 1)
idx2 = slice(1, None)
print(arr[idx1, idx2])

以上两种索引方式都是支持的。

  1. 如果确实需要使用tuple类型的索引,可以使用numpy的take函数,如下示例:

import numpy as np
arr = np.array([[1, 2], [3, 4]])
idx = (0, 1)
print(np.take(arr, idx))

这种方式可以正常输出结果,但需要将tuple转换为整数或者整数数组。

综上所述,出现”TypeError:list indices must be integers or slices,not tuple”这个错误时,通常是由于使用了tuple类型的索引,而numpy数组不支持tuple索引。需要修改代码,使用整数或切片类型的索引,或者使用numpy的take函数。