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)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)