我正在尝试这个网址的例子. http://cython.readthedocs.io/en/latest/src/userguide/buffer.html
为了测试它我做了以下.
import pyximportpyximport.install(build_dir = 'build')import ctestm = ctest.Matrix(10)m.add_row()print(m)
当我调用m.add_row()函数时,这给了我一个错误
TypeError:’int’对象不可迭代
在类中,add_row定义为
from cpython cimport Py_bufferfrom libcpp.vector cimport vectorcdef class Matrix: cdef Py_ssize_t ncols cdef Py_ssize_t shape[2] cdef Py_ssize_t strides[2] cdef vector[float] v def __cinit__(self, Py_ssize_t ncols): self.ncols = ncols def add_row(self): """Adds a row, initially zero-filled.""" self.v.extend(self.ncols) ...
这个错误对我来说是完全合理的,假设在cython中对vector进行调用扩展与在python列表上扩展完全相同.您不传递数字,而是传递给列表的可迭代对象.
我可以通过这样做来解决它…
def add_row(self): """Adds a row, initially zero-filled.""" self.v.extend([0] * self.ncols)
我只是想知道示例中是否存在拼写错误,或者我是否遗漏了某些内容.扩展函数在哪里来自向量?在使用cython发布的vector.pxd文件中,它永远不会导入扩展函数,甚至不存在于c标准库中. cython是否对矢量类型做了一些特别的事情?
https://github.com/cython/cython/blob/master/Cython/Includes/libcpp/vector.pxd
解决方法:
cpp向量可以自动转换为python列表.通过检查self.v.extend([0] * self.ncols)行的c代码,创建了一个新的python列表:__ pyx_t_2 = PyList_New(1 *((__ pyx_v_self-> ncols< 0)?0:__ pyx_v_self - > NCOLS)).因此extend实际上是python list的extend方法.这种自动转换也可以通过以下代码进行验证(在jupyter笔记本中):
%%cython - from libcpp.vector cimport vectordef test_cpp_vector_to_pylist(): cdef vector[int] cv for i in range(10): cv.push_back(i) return cva = test_cpp_vector_to_pylist()print a # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]print type(a) # <type 'list'>
但是,在这种情况下,cv会转换为临时python列表,原始cpp vertor将保持不变,如下面的代码所示:
%%cython - from libcpp.vector cimport vectordef test_cpp_vector_to_pylist_1(): cdef vector[int] cv for i in range(10): cv.append(i) # Note: the append method of python list return cva = test_cpp_vector_to_pylist_1()print a # []print type(a) # <type 'list'>
另外,c数组也可以自动转换为python列表:
%%cythondef test_c_array_to_pylist(): cdef int i cdef int[10] ca for i in range(10): ca[i] = i return caa = test_c_array_to_pylist()print a # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]print type(a) # <type 'list'>
来源:https://www.icode9.com/content-1-288901.html
联系客服