gpt4 book ai didi

python - 如何将 Cython 数组转换为 Python 对象以便返回结果?

转载 作者:太空宇宙 更新时间:2023-11-04 02:47:51 24 4
gpt4 key购买 nike

令我惊讶的是,没有关于将 Cython 数组转换为 Python 对象的文档。任何建议将不胜感激。

# Values are a list of integers containing numerators and denominators 
def test_looping_ndarray_nd_list(list matrix):

cdef int *my_ints
cdef i

# Allocate memory to store ctype integers in memory
my_ints = <int *>malloc(len(matrix)*cython.sizeof(int))
if my_ints is NULL:
raise MemoryError()

for i in xrange(len(matrix)): # Convert to ctypes
my_ints[i] = matrix[i]

# How do I convert my_ints to Python object so I can return the result???

return

最佳答案

我会使用类型化的内存 View 来做到这一点:

import numpy as np
cimport numpy as np
cimport cython

# Values are a list of integers containing numerators and denominators
@cython.boundscheck(False)
def test_looping_ndarray_nd_list(list matrix):

cdef np.intp_t[:] my_ints
cdef int i

# Allocate memory to store ctype integers in memory
my_ints = np.array(matrix, dtype='int')

# do some work while releasing the GIL
with nogil:
for i in range(my_ints.shape[0]):
my_ints[i] = 2*my_ints[i]

return np.asarray(my_ints).tolist()

关于python - 如何将 Cython 数组转换为 Python 对象以便返回结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com