我在 Python3 中使用 Numba 库。
函数的参数是一个二维数组。
我将 Numba jit 装饰器设置为 list[list[int]],但在运行代码后显示 TypeError: 'type' object is not subscriptable。
我使用 print(numba.typeof(matrix)) 来检测参数类型,它返回 list(reflected list(int32)) 类型。
但即使我将装饰器更改为 list[list[numba.int32]] ,也无法正常工作。
代码:
from numba import jit
size = 3
matrix = [[0, 1, 2], [4, 5, 6], [7, 8, 9]]
@jit(list[list[int]])
def test(jitmatrix):
_total = 0
for i in range(size):
for j in range(size):
_total += jitmatrix[j][i]
test(matrix)
有没有想过在没有 numpy 库的情况下在 jit 装饰器上设置二维数组?
还是必须使用numpy库?
请您参考如下方法:
从 0.44 开始,Numba 不支持列表列表作为 nopython 模式下函数的输入。见:
http://numba.pydata.org/numba-doc/latest/reference/pysupported.html#list-reflection
在 @jit 的参数中,numba 不知道 list 并且不能自动将其转换为任何 numba 类型。 TypeError ... subscriptable 错误来自 python 本身,因为您正在尝试访问内置类型的元素(在本例中为 list),它是不允许。
不过下面的方法是可行的:
from numba import jit
import numba as nb
import numpy as np
size = 3
matrix = np.array([[0, 1, 2], [4, 5, 6], [7, 8, 9]])
@jit(nopython=True)
# or @jit(nb.int64(nb.int64[:,:]))
def test(jitmatrix):
_total = 0
for i in range(size):
for j in range(size):
_total += jitmatrix[j,i] # note the change in indexing, which is faster
return _total
test(matrix)
