如何将numpy ndarrays列表作为向量传递给cython

时间:2015-03-24 00:58:25

标签: python arrays list numpy cython

如何将numpy ndarray列表传递给cython?让我们说列表l(下面定义)的所有元素都是2d浮点数组,但它们可能有不同的行数和列数,所以我不能将它们全部堆叠成一个单个numpy数组。

l = [np.zeros(i, 2 * i) for i in [5, 6, 7]]

我能够通过使用vector[np.int_t]作为函数的参数将整数列表传递给cython,但是我没有成功通过使用vector[np.ndarray]或{{传递ndarrays列表1}}

1 个答案:

答案 0 :(得分:3)

正如@hpaulj所指出的,您可以将列表作为声明的输入参数传递,然后声明一个“接收”列表中每个元素的缓冲区。通过这种方式,您可以以最高效率迭代列表和数组。这可以编码为:

def test(list list_of_2darrays):
    cdef np.ndarray[ndim=2, dtype=np.float64_t] buff2d # check your dtype
    cdef int i, j

    for buff2d in list_of_2darrays:
        for i in range(buff2d.shape[0]):
            for j in range(buff2d.shape[1]):
                buff2d[i, j] += i + j