Python 列表到 Cython

标签 python arrays cython

我想知道如何使用 Cython 将普通 python 列表转换为 C 列表,处理它并返回一个 python 列表。喜欢:

Python 脚本:

import mymodule

a = [1,2,3,4,5,6]
len = len(a)
print(mymodule.process(a,len))

Cython 脚本(mymodule.pyd):

cpdef process(a, int len):
    cdef float y
    for i in range(len):
        y = a[i]
        a[i] = y * 2
    return a

我阅读了有关 MemoryView 和许多其他内容的信息,但我并没有真正理解发生了什么,并且很多示例都使用了 Numpy(我不想使用它来避免我的脚本的用户下载一个大包......无论如何我认为它不适用于我的软件)。我需要一个非常简单的示例来准确理解正在发生的事情。

最佳答案

您需要将列表的内容显式复制到数组中。例如……

cimport cython
from libc.stdlib cimport malloc, free

...

def process(a, int len):

    cdef int *my_ints

    my_ints = <int *>malloc(len(a)*cython.sizeof(int))
    if my_ints is NULL:
        raise MemoryError()

    for i in xrange(len(a)):
        my_ints[i] = a[i]

    with nogil:
        #Once you convert all of your Python types to C types, then you can release the GIL and do the real work
        ...
        free(my_ints)

    #convert back to python return type
    return value

关于Python 列表到 Cython,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14780007/

相关文章:

python - 为什么与像 None 这样的单例比较应该总是用 is 或 is not 来完成?

java - String.Split() 用于字符串数组并保存到新数组中

python - 如何加速 itertools 组合?

python - Matplotlib - 来自已创建绘图的子图

python - 最近的交叉点到 python 中的多条线

python - 如何使用 Python 3.x 阅读和编辑 Google 电子表格?

java - 如何让 JOOQ 在 IN 子句中使用数组

javascript - 在二维数组js中选择对象

arrays - Cython 多处理共享内存

python - 识别方法是用 Python 还是 Cython 编写的