首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cython和数组

Cython和数组
EN

Stack Overflow用户
提问于 2013-12-18 18:03:17
回答 2查看 1.6K关注 0票数 3

我正试着用Cython来加速一些课程。但我仍然希望代码也能在纯Python中运行。

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

代码语言:javascript
复制
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中:

代码语言:javascript
复制
 import cython

 cdef class A
     cdef int[8] S

     cdef test(self)

但是Cython抱怨编译:

代码语言:javascript
复制
Cannot convert Python object to 'int [8]'
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-19 07:13:26

我终于开始工作了:

代码语言:javascript
复制
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:

代码语言:javascript
复制
cimport cpython.array

cdef class RC4:
    cdef int [:] S
    cdef int test(self)
票数 3
EN

Stack Overflow用户

发布于 2013-12-18 18:17:48

这是因为语法错误,更像是:

代码语言:javascript
复制
cdef int S[8]

而且,没有必要使用import cython

这实际上是在cython文档一开始就定义的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20665249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档