2013-02-12 113 views
2

我有一个在cython中的列表,并希望切片而不使用python对象(为了速度)。如何在cython中切片列表

cdef int len = 100  
cdef int *q 
cdef int *r 

q = <int *>malloc(len *cython.sizeof(int)) 

r = q[50:] 

和得到这个错误:

r = q[50:] 
    ^
------------------------------------------------------------ 

hello.pyx:24:9: Slicing is not currently supported for 'int *'. 

有一个有效的方式来做到这一点? “......目前不支持......”让我有点害怕。 我使用cython 0.18

+0

'q'不是一个列表,而是一个本地数组。我猜你必须使用较低级别的东西来处理这些问题。 (围绕一个数组和一个start + end索引。) – millimoose 2013-02-12 19:29:27

+0

@millimoose我看看在doc中的memoryview的东西,但我无法使它与我的简单示例一起工作。我是新的cython和C编程。你是什​​么意思让你谈论低层和“传递数组和开始+结束索引”? thanx – 2013-02-12 19:48:45

+0

在C中,当处理数组时,通常不只是使用数组,而是使用'start'和'length'参数来指示函数应该工作的数组部分。数组和两个索引一起表示一个“切片”。 (如果你看一些快速排序的例子,你可以看到这个例子。)也就是说,这对Cython来说可能是过分的矫枉过正,我对此并不熟悉。 – millimoose 2013-02-12 19:58:50

回答

3

快速切片和其他一些很酷的东西是可能的通过类型化的Memoryviews。但为了进行切片,您需要一些关于数组的元数据,所以最好使用数组类型而不是普通指针。查阅文档以获取更多信息:http://docs.cython.org/src/userguide/memoryviews.html

你的问题的修改给出了:

cdef int q_array[5] # c array 
cdef int[:] q # 1D memview 
cdef int[:] r # another 1D memview 

q = q_array # point q to data 
r = q[2:] # point r to a slice of q 

r[0] = 5 # modify r 

# test                  
print q[2] 
print r[0] 

你仍然可以从片创建的指针,如果你真的想它坏:

# ... 

cdef int* r_ptr 
cdef int* q_ptr 

r_ptr = &r[0] 
q_ptr = &q[0] 

print q_ptr[2] 
print r_ptr[0] 

与numpy的阵列也适用

import numpy as np 

cdef int[:] q = np.arange(100).astype('int32') # slow 
cdef int[:] r 

r = q[50:] # fast slicing 

print r[0] 
+0

好吧,你的例子帮助我了解更多memview如何工作切片阵列。但是当我尝试使用memview声明来编译任何代码时,出现错误。每次我添加一行如下:cdef int [:] r – 2013-02-13 13:13:03

+0

1)你得到什么错误? 2)你如何编译代码? – dmytro 2013-02-13 16:34:58

+0

我按照cython文档中的描述进行编译。标准setup.py和我在Windows 7 64bit上使用gcc(MinGW)。这里是错误的一部分(太长):build \ temp.win32-3.3 \ Release \ hello.o:hello.c :(。text + 0x1032):未定义的引用到__sync_fetch_and_sub_4 build \ temp.win32- 3.3 \ Release \ hello.o:hello.c :(.text + 0x21e5):未定义引用__sync_fetch_and_add_4 build \ temp.win32-3.3 \ Release \ hello.o:hello.c :(.text + 0xa3d0) :'__sync_fetch_and_sub_4'的未定义引用 collect2:ld aretourné1代码未完成 错误:命令'gcc'失败,退出状态为1 – 2013-02-13 20:08:33