首页 > 解决方案 > 切片索引必须是整数,它已经是它了。如何超越这个?

问题描述

我在数组和矩阵上测试了这个函数;它给出了关于切片索引的相同类型错误。双 / 被使用,所以我的指数真的是一个整数。

def getpar(PSI):
    n = PSI.shape[0]
    x = n//2+1
    gamma = PSI[0:x]
    c = PSI[(x + 1):n]
    return gamma,c

getpar(np.matrix([[1,2,3],[1,2,3],[2,4,5],[2,5,2]]))

看来 x 的计算是个问题。

> Traceback (most recent call last):
  File "C:\Users\Azerty\PycharmProjects\toto\venv37\lib\site-packages\IPython\core\interactiveshell.py", line 3325, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-20-f29d42dbbc56>", line 1, in <module>
    getpar(np.matrix([[1,2,3],[1,2,3],[2,4,5],[2,5,2]]))
  File "C:/Users/Azerty/PycharmProjects/toto/venv37/HARST/HARST.py", line 12, in getpar
    x = itn//2+1
  File "C:\Users\Azerty\PycharmProjects\toto\venv37\lib\site-packages\numpy\matrixlib\defmatrix.py", line 195, in __getitem__
    out = N.ndarray.__getitem__(self, index)
TypeError: slice indices must be integers or None or have an __index__ method

标签: pythonpython-3.xnumpy

解决方案


您的问题是您正在使用浮点数来索引数组。numpy 浮点数不能使用//. 所以你可以这样做:

x = int(n//2+1)

你也可以print(x, type(x)),你会看到它是什么。


推荐阅读