打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python – Cython缓冲区协议示例错误

我正在尝试这个网址的例子. 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 - &GT 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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Cython应用手记
C 一级的构造函数和析构函数
用Cython加速Python到“起飞”
[学习Cython编程]C中使用Python标准库
Cython学习
提速30倍! 这个加速包让Python代码飞起来
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服