【发布时间】:2017-07-21 11:23:01
【问题描述】:
我想使用 Cython 处理大量固定长度字符串的函数。对于标准的 cython 函数,我可以像这样声明数组的类型:
cpdef double[:] g(double[:] in_arr):
cdef double[:] out_arr = np.zeros(in_arr.shape, dtype='float64')
cdef i
for i in range(len(in_arr)):
out_arr[i] = in_arr[i]
return out_arr
当 dtype 是 int32、float、double 等简单的 dtype 时,它会按预期编译和工作。但是,我无法弄清楚如何创建固定长度字符串的类型化内存视图 - 即例如,相当于np.dtype('a5')。
如果我使用这个:
cpdef str[:] f(str[:] in_arr):
# arr should be a numpy array of 5-character strings
cdef str[:] out_arr = np.zeros(in_arr.shape, dtype='a5')
cdef i
for i in range(len(in_arr)):
out_arr[i] = in_arr[i]
return out_arr
函数可以编译,但是这样:
in_arr = np.array(['12345', '67890', '22343'], dtype='a5')
f(in_arr)
抛出以下错误:
---> 16 cpdef str[:] f(str[:] in_arr): 17 # arr 应该是一个由 5 个字符组成的 numpy 数组 18 cdef str[:] out_arr = np.zeros(in_arr.shape, dtype='a5')
ValueError: 缓冲区 dtype 不匹配,预期为 'unicode object' 但得到了 字符串
类似地,如果我使用bytes[:],它会给出错误“缓冲区 dtype 不匹配,预期为 'bytes object' 但得到了一个字符串”——这甚至没有解决我没有指定的问题这些字符串的长度为 6。
有趣的是,我可以在结构化类型中包含固定长度的字符串,如this question,但我认为这不是声明类型的正确方法。
【问题讨论】:
标签: python python-3.x numpy cython