I'm trying to compile this kind of code:
def my_func(double c, int m):
cdef double f[m][m]
f = [[c for x in range(m)] for y in range(m)]
...
which raises:
Error compiling Cython file:
------------------------------------------------------------
def grow(double alpha, double beta, double gamma, int m, int s):
cdef double f[m][m]
^
------------------------------------------------------------
test.pyx:6:22: Not allowed in a constant expression
after which I assume I can't use variable at the pointed place and I try with numeric value:
def my_func(double c, int m):
cdef double f[500][500]
f = [[c for x in range(500)] for y in range(500)]
...
but then I get:
Error compiling Cython file:
------------------------------------------------------------
f = [[beta for x in range(500)] for y in range(500)]
^
------------------------------------------------------------
test.pyx:13:6: Assignment to non-lvalue 'f'
So, I'm wondering how to declare and make 2D list in cython code. I couldn't find this kind of example in documentation of googling for "cython 2D list"
Do not use list comprehension in Cython. There are not speedups as they create regular python list. Wiki says, that you should use dynamic allocation in Cython as follow:
from libc.stdlib cimport malloc, free
def my_func(double c, int m):
cdef int x
cdef int y
cdef double *my_array = <double *>malloc(m * m * sizeof(double))
try:
for y in range(m):
for x in range(m):
#Row major array access
my_array[ x + y * m ] = c
#do some thing with my_array
finally:
free( my_array )
But if you need to have a python object of a 2D array, its recommended to use NumPy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With