python - 切片索引必须是整数,它已经是它了。如何超越这个?
问题描述
我在数组和矩阵上测试了这个函数;它给出了关于切片索引的相同类型错误。双 / 被使用,所以我的指数真的是一个整数。
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
解决方案
您的问题是您正在使用浮点数来索引数组。numpy 浮点数不能使用//
. 所以你可以这样做:
x = int(n//2+1)
你也可以print(x, type(x))
,你会看到它是什么。
推荐阅读
- git - 将 SVN 主干中的每个目录转换为不同的 GIT 存储库
- import - 将 Canva 设计导入 Webflow
- javascript - 如何在内容可编辑元素的根级别列表之后创建下一段?
- php - 每页都需要页脚和页眉,但错误 500
- javascript - 如何在 Visual Studio 中使用机密?
- node.js - 使用 graphql apollo 客户端发送 httpOnly cookie
- android - 为什么 Android 应用程序在一次启动时启动 3 次?
- python - Matplotlib 崩溃,退出代码为 -1073741819 (0xC0000005)
- flutter - Flutter:是否可以不按按钮自动切换屏幕?
- python - Python git项目结构约定?