python - 如何在没有 numpy 的情况下在 jit 装饰器上设置二维数组?

标签 python arrays python-3.x numpy numba

我在 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)

关于python - 如何在没有 numpy 的情况下在 jit 装饰器上设置二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56804571/

相关文章:

python - pip 安装 ortools : No matching distribution - Alpine

php - 在网页上显示来自 SSH 可访问文件的实时数据的最佳方式

python - 将 2d dict 的 dict 内的值除以与该键匹配的另一个 dicts 值

python - 在 Python 中使用 xlwt 在 Excel 中生成折线图

mysql - 如何查找数据库中的总行数

python - 将两个数组按元素相乘,其中一个数组将数组作为元素

javascript - 使用 lodash 合并 2 个数组

python - 无法使用任何方法使用 python (3.8) 脚本打开 Microsoft Teams

python - matplotlib.pyplot.draw() 和 matplotlib.pyplot.show() 没有效果

python - 通过后台线程访问 Tkinter 的文本小部件会导致崩溃