Cython函数中的Lambda表达

Man*_*oel 7 python lambda cython python-3.x

我想将lambda表达式与cython一起使用,但不适用于cpdef。该错误表明尚不支持该错误,但是cython changeleg则表明支持lambda表达式。

%%cython
cimport numpy as np
import numpy as np

cdef foo():
    a = np.random.randint(1,10,10)
    b = sorted(a, key = lambda x: x%np.pi)   #Compiles
    return(b)

cpdef goo():
    a = np.random.randint(1,10,10)
    b = sorted(a)    #Compiles
    return(b)

cpdef hoo():
    a = np.random.randint(1,10,10)
    b = sorted(a, key = lambda x: x%np.pi)   #Compile time error
    return(b)
Run Code Online (Sandbox Code Playgroud)
Error compiling Cython file:
------------------------------------------------------------
...
cpdef goo():
    a = np.random.randint(1,10,10)
    b = sorted(a) 
    return(b)

cpdef hoo():
     ^
------------------------------------------------------------

/********/.cache/ipython/cython/_cython_magic_63378538fa4250ed3135e0289d6af7a0.pyx:14:6: closures inside cpdef functions not yet supported
Run Code Online (Sandbox Code Playgroud)

确实不支持lambda表达式的情况还是我缺少了什么?

Python版本3.5.5;Cython版本:0.24

小智 2

这仅涉及 cpdef 方法内的闭包。如果您没有在 cpdef 函数内定义任何函数(即闭包),则这将起作用。Lambda表达式只是一个函数,但是有特定的语法。尝试这个。

def sort_key(x):
   return x%np.pi

cpdef hoo():
   a = np.random.randint(1,10,10)
   b = sorted(a, key = sort_key)
   return(b)
Run Code Online (Sandbox Code Playgroud)