【问题标题】:how to slice list in cython如何在cython中切片列表
【发布时间】:2013-01-28 04:55:03
【问题描述】:

我在 cython 中有一个列表,想在不使用 python 对象的情况下对其进行切片(为了速度)。

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

【问题讨论】:

  • q 不是一个列表,而是一个原生数组。我猜你将不得不使用较低级别的东西来处理这些。 (传递一个数组和一个开始+结束索引。)
  • @millimoose 我看了一下文档中的 memoryview 内容,但我无法使用我的简单示例使其工作。我是 cython 和 C 编程的新手。你是什​​么意思想让你谈论低级和“传递数组和开始+结束索引”?谢谢
  • 在 C 语言中,当您使用数组时,通常不仅仅使用数组,而是使用 startlength 参数来指示函数应该在数组的哪一部分继续工作。数组和两个索引一起代表一个“切片”。 (例如,如果您查看一些用于快速排序的示例代码,您可以看到这一点。)也就是说,这对于我不太熟悉的 Cython 来说可能是非常过分的。
  • @millimoose 你能告诉我在哪里可以找到快速排序的示例代码吗?这正是我需要对数组进行切片的原因,以便为实现 KDtree 制作许多 qsort(我已经在 python 中做过,但需要将其转移到 cython 以提高速度)

标签: python list cython slice


【解决方案1】:

通过 Typed 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]

【讨论】:

  • 好的,您的示例帮助我更多地了解 memview 如何用于切片数组。但是当我尝试使用 memview 声明编译任何代码时出现错误。每次我添加一行:cdef int[:] r
  • 我按照 cython 文档中的描述编译它。标准 setup.py,我在 windows 7 64 位上使用 gcc (MinGW)。这是错误的一部分(太长): build\temp.win32-3.3\Release\hello.o:hello.c:(.text+0x1032): undefined reference to __sync_fetch_and_sub_4' build\temp.win32-3.3\Release\hello.o:hello.c:(.text+0x21e5): undefined reference to __sync_fetch_and_add_4' build\temp.win32 -3.3\Release\hello.o:hello.c:(.text+0xa3d0): undefined reference to `__sync_fetch_and_sub_4' collect2: ld a retourné 1 code d'état d'execution error: command 'gcc' failed with exit status 1
  • hm... 错误可能在 pyx-->c 阶段。启动“cython -a hello.pyx”时一切顺利吗?
  • 我在 cython 的邮件组上发布了错误,他们认为这听起来像是 Python 3.3 的错误。因为它似乎适用于 python 2.7。你用的是什么版本?我:Python 3.3 与 cython 0.18 和 MinWG GCC 4.6.2
  • 哦,我明白了,这很可能是 Py3k 问题...我在 Linux 下使用 Python-2.7,从未尝试过使用 python 3。
猜你喜欢
  • 2016-02-23
  • 1970-01-01
  • 2018-04-05
  • 2010-12-14
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
相关资源
最近更新 更多