TypeError: slice indices must be integers or None or have an __index__ method
目标
今天给大家带来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,小编的报错代码片段位置如下:
# 现在在每个级别中添加左右两半图像
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:]))
修改后,此报错提示就消失了~~
如果文章对你有帮助,欢迎一键三连哦~~

Python TypeError: slice indices解析及解决方案
本文介绍了Python中TypeError: slice indices must be integers错误的原因,该错误通常由使用浮点数作为切片索引导致。文章详细分析了Python 3.x和2.x中整数除法的区别,并提供了解决此类问题的方法,即确保使用整数进行切片操作。
1153





