2013-02-12 115 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