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

栏目: Python · 发布时间: 8年前

内容简介:TypeError: slice indices must be integers or None or have an __index__ method

执行如下 Python 脚本时

import numpy as np
 
dy = [0,1,2]
edy = [0,1,2]
 
dy[0:2] = np.fix(dy[0:2])
edy[0:2] = np.fix(edy[0:2])
 
box = [[1,2,3,4],[3,4,5,6]]
box2 = [[7,8,9,10],[11,12,13,14]]
 
box2 = box[dy[0]:edy[2]]

会遇到错误信息

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    box2 = box[dy[0]:edy[2]]
TypeError: slice indices must be integers or None or have an __index__ method

这个提示非常具有迷惑性,会让人不知所措。

其实非常简单

dy[0:2] = np.fix(dy[0:2])

这行导致整个数组变成了浮点数格式的数组,可以试着打印出结果,就会发现整个里面的数字完全变成了浮点数。

而浮点数是不可以用来作为数组的下标的。

修改成如下方式即可

import numpy as np
 
dy = [0,1,2]
edy = [0,1,2]
 
dy[0:2] = np.fix(dy[0:2])
edy[0:2] = np.fix(edy[0:2])
 
box = [[1,2,3,4],[3,4,5,6]]
box2 = [[7,8,9,10],[11,12,13,14]]
 
box2 = box[int(dy[0]):int(edy[2])]

请注意最后的

int()

函数,强制转换浮点数为整数。

参考链接

错误异常slice indices must be integers or None or have


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Looking For a Challenge

Looking For a Challenge

the University of Warsaw / the University of Warsaw / 2012-11 / 0

LOOKING FOR PROGRAMMING CHALLENGES? Then this book is for you! Whether it's the feeling of great satisfaction from solving a complex problem set, or the frustration of being unable to solve a task,......一起来看看 《Looking For a Challenge》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具