本文介绍了快速字符串数组 - Cython的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有以下假设代码:
cdef extern from "string.h":
int strcmp(char* str1, char* str2)
def foo(list_str1, list_str2):
cdef unsigned int i, j
c_arr1 = ??
c_arr2 = ??
for i in xrange(len(list_str1)):
for j in xrange(len(list_str2)):
if not strcmp(c_arr1[i], c_arr2[j]):
do some funny stuff
有什么方法可以将列表转换为 c 数组吗?
is there some way how to convert the lists to c arrays?
我已经阅读并尝试过 Cython - 将字符串列表转换为字符 ** 但这只会引发错误.
I have read and tried Cython - converting list of strings to char ** but that only throws errors.
推荐答案
试试下面的代码.下面代码中的to_cstring_array
函数就是你想要的.
Try following code. to_cstring_array
function in the following code is what you want.
from libc.stdlib cimport malloc, free
from libc.string cimport strcmp
from cpython.string cimport PyString_AsString
cdef char ** to_cstring_array(list_str):
cdef char **ret = <char **>malloc(len(list_str) * sizeof(char *))
for i in xrange(len(list_str)):
ret[i] = PyString_AsString(list_str[i])
return ret
def foo(list_str1, list_str2):
cdef unsigned int i, j
cdef char **c_arr1 = to_cstring_array(list_str1)
cdef char **c_arr2 = to_cstring_array(list_str2)
for i in xrange(len(list_str1)):
for j in xrange(len(list_str2)):
if i != j and strcmp(c_arr1[i], c_arr2[j]) == 0:
print i, j, list_str1[i]
free(c_arr1)
free(c_arr2)
foo(['hello', 'python', 'world'], ['python', 'rules'])
这篇关于快速字符串数组 - Cython的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!