How to declare 2D list in Cython

后端 未结 2 961
刺人心
刺人心 2020-12-31 15:41

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)]
    ...
         


        
2条回答
  •  悲哀的现实
    2020-12-31 15:50

    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 = 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.

提交回复
热议问题