TypeError: slice indices must be integers or None or have an __index__ method

  • 目标
  • 1. 错误提示
  • 2. 错误原因
  • 3. 解决方案

目标

今天给大家带来Python程序中报错TypeError: slice indices must be integers or None or have an __index__ method的解决办法,希望能够帮助到大家。

1. 错误提示

在执行Python3程序时,错误提示TypeError: slice indices must be integers or None or have an __index__ method,www.887551.com的报错代码片段位置如下:

# 现在在每个级别中添加左右两半图像
LS = []
for la, lb in zip(lpA, lpB):
    rows, cols, dpt = la.shape
    ls = np.hstack((la[:, 0:cols/2], lb[:, cols/2:]))
    LS.append(ls)

提示的出错代码行为:

ls = np.hstack((la[:, 0:cols / 2], lb[:, cols / 2:]))

2. 错误原因

在Python 3.x中,5/2将返回2.5,而5 // 2将返回2。前者是浮点除法,后者是整数除法。

在Python 2.2或更高版本的2.x行中,除非您执行from __future__导入除法,否则整数没有区别,这会导致Python 2.x采取3.x行为。

不论将来如何导入,5.0 // 2都将返回2.0,因为这是该操作的最低划分结果。

3. 解决方案

将出错代码行修改为:

ls = np.hstack((la[:, 0:cols // 2], lb[:, cols // 2:]))

修改后,此报错提示就消失了~~

如果文章对你有帮助,欢迎一键三连哦~~

本文地址:https://blog.csdn.net/DIPDWC/article/details/111938260