Python 列表到 Cython [英] Python list to Cython

查看:36
本文介绍了Python 列表到 Cython的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to know how to convert normal python list to C list with Cython , process it and return a python list. Like:

Python 脚本:

import mymodule

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

Cython 脚本(mymodule.pyd):

Cython script (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(我不想使用它来避免我的脚本用户下载一个大包......无论如何我认为它不适用于我的软件).我需要一个非常简单的例子来理解到底发生了什么.

I read about MemoryView and many others things but I not really unterstand what happen and a lot of example use Numpy ( I don't want to use it for avoid user of my script download a big package ... anyway I think it's don't work with my software ). I need a really simple example to understand what's happening exactly.

推荐答案

您需要明确地将列表的内容复制到数组中.例如...

You'll need to copy the contents of the list to an array explicitly. For example...

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆