简体   繁体   English

cython函数中的Lambda表达式

[英]Lambda expression in cython function

I want to use lambda expression with cython but it is not working with cpdef. 我想在cython中使用lambda表达式,但它不能与cpdef一起使用。 The error says that it is not yet supported, but cython changeleg says that lambda expressions are supported. 该错误表明它尚未受支持,但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)

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

Is it indeed the case that lambda expressions are not supported or am I missing something? 是否确实不支持lambda表达式或者我错过了什么?

Python version 3.5.5; Python版本3.5.5; Cython version: 0.24 Cython版本:0.24

This only about closures inside cpdef methods. 这只是关于cpdef方法内部的闭包。 If you do not define any function inside cpdef function, ie closures, this would work. 如果你没有在cpdef函数中定义任何函数,即闭包,这将起作用。 Lambda expression is just a functions, but with specific syntax. Lambda表达式只是一个函数,但具有特定的语法。 Try this. 试试这个。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM