内容简介: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
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Heuristic Search
Stefan Edelkamp、Stefan Schrodl / Morgan Kaufmann / 2011-7-15 / USD 89.95
Search has been vital to artificial intelligence from the very beginning as a core technique in problem solving. The authors present a thorough overview of heuristic search with a balance of discussio......一起来看看 《Heuristic Search》 这本书的介绍吧!