[英]Cython function in pure python mode returning an list of strings
我正在尝试转换以下 python 函数:
def python_compare(a: str, b: str) -> list:
n = len(a)
result = []
for i in range(n):
letter1 = a[i]
letter2 = b[i]
if letter1 != letter2:
mut = f'{letter1}{i}{letter2}'
result.append(mut)
return result
python_compare('aaa', 'aab')
output: ['a2b']
以纯 python 模式编写的 cython 函数。
我在 jupyter notebook 中运行代码,因此是%%cython
行。 这就是我正在尝试的:
%%cython -a
import cython
@cython.cfunc
def compare(a: cython.basestring, b: cython.basestring) -> cython.array:
n = cython.int = len(a)
i: cython.int
letter1: cython.basestring
letter2: cython.basestring
mut: cython.basestring
result: cython.array(cython.basestring, n)
for i in range(n):
letter1 = a[i]
letter2 = b[i]
if letter1 != letter2:
mut = f'{letter1}{i}{letter2}'
result.append(mut)
return result
但是,这给了我输出:
Error compiling Cython file:
------------------------------------------------------------
...
import cython
@cython.cfunc
def compare(a: cython.basestring, b: cython.basestring) -> cython.array:
^
------------------------------------------------------------
8a1.pyx:5:65: Not a type
Error compiling Cython file:
------------------------------------------------------------
...
import cython
@cython.cfunc
def compare(a: cython.basestring, b: cython.basestring) -> cython.array:
^
------------------------------------------------------------
8a1.pyx:5:21: 'basestring' not a valid cython attribute or is being used incorrectly
Error compiling Cython file:
------------------------------------------------------------
...
import cython
@cython.cfunc
def compare(a: cython.basestring, b: cython.basestring) -> cython.array:
^
------------------------------------------------------------
8a1.pyx:5:43: 'basestring' not a valid cython attribute or is being used incorrectly
Error compiling Cython file:
------------------------------------------------------------
...
letter1 = a[i]
letter2 = b[i]
if letter1 != letter2:
mut = f'{letter1}{i}{letter2}'
result.append(mut)
^
------------------------------------------------------------
8a1.pyx:20:12: local variable 'result' referenced before assignment
Error compiling Cython file:
------------------------------------------------------------
...
letter2 = b[i]
if letter1 != letter2:
mut = f'{letter1}{i}{letter2}'
result.append(mut)
return result
^
------------------------------------------------------------
8a1.pyx:21:11: local variable 'result' referenced before assignment
有人可以帮我在 cythons 纯 python 模式下重写函数,以便它编译和工作吗?
非常感谢所有建议和意见! 谢谢,
威廉
我不是 Cython 专家,但似乎您在尝试向其附加内容之前没有创建result
数组(错误消息是一个强烈的提示:“局部变量'结果'在赋值之前引用”)。 似乎您只声明了它的类型( result: cython.array(cython.basestring, n)
),然后在尝试追加之前不要给这个变量分配任何东西。
顺便说一句,真的可以append
到数组吗? 您声明了一定大小( n
)的东西。 append
应该增加这个数组的大小吗? 如果不是,应该在数组中的哪个位置插入数据?
在您的纯 Python 代码中,您从一个空列表开始。 然后你把东西附加到最后。 这看起来不错,但可能无法在 Cython 中使用数组进行字面翻译。
我对非 Cython 专家的直觉是,您应该就地修改值(C 风格),而不是附加到数组中,为此,您需要一个索引。 你的循环变量i
可以扮演这个角色吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.