Cython和数组(Cython and arrays)

编程入门 行业动态 更新时间:2024-10-24 10:14:17
Cython和数组(Cython and arrays)

我正在尝试使用Cython加速某些课程。 但我仍然希望代码也可以在纯Python中运行。

如何在类中定义数组(代码已经简化)

import cython class A: def __init__(self): if cython.compiled: # This will work in Cython for k in len(self.S): self.S[k]=k else: # This will work in interpreter self.S=range(8) def test(self): self.S[0]+=1

并在.pxd中:

import cython cdef class A cdef int[8] S cdef test(self)

但是Cython抱怨编译:

Cannot convert Python object to 'int [8]'

I am trying to Cython to speed up some class. But I still want the code to run in pure Python too.

How do I define an array in an class (code has been simplified)

import cython class A: def __init__(self): if cython.compiled: # This will work in Cython for k in len(self.S): self.S[k]=k else: # This will work in interpreter self.S=range(8) def test(self): self.S[0]+=1

And in the .pxd:

import cython cdef class A cdef int[8] S cdef test(self)

But Cython complains on compilation:

Cannot convert Python object to 'int [8]'

最满意答案

我终于得到了它的工作:

import array class A: def __init__(self): # This will work in Cython self.S=array.array("l", range(8)) def test(self): self.S[0]+=1

和.pxd:

cimport cpython.array cdef class RC4: cdef int [:] S cdef int next(self)

I finally got it to work:

import array class A: def __init__(self): # This will work in Cython self.S=array.array("l", range(8)) def test(self): self.S[0]+=1

And .pxd:

cimport cpython.array cdef class RC4: cdef int [:] S cdef int next(self)

更多推荐

本文发布于:2023-08-07 20:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465610.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Cython   arrays

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!