如何使用 numba 操作列表生成器

问题描述:

我正在尝试使用一个尝试使用 numba 和列表生成器的简单代码,但在执行以下代码时出现错误.

I'm trying to use a simple code that tries to use numba and list generator and I get an error executing the following code.

@numba.jit(nopython=True, nogil=True)
def perform_search(simple_list, number):
    gen = (ind for ind in xrange(len(simple_list)) if simple_list[ind] != number)
    return next(gen)

x = [1,1,1,2,1,3]
perform_search(x, 1)

当我执行上面的代码时,我得到一个 ValueError,但是,当只使用装饰器 @numba.jit 时,我得到一个 LoweringError>.

When I execute the above code I get a ValueError, however, when just use the decorator @numba.jit, I get a a LoweringError.

请帮助我使用生成器(或其他方式)执行这个简单的搜索.提前致谢

Please help me to perform this simple search using generator (or otherwise). Thanks in advance

你有什么

gen = (ind for ind in xrange(len(simple_list)) if simple_list[ind] != number)

是一个生成器表达式,目前numba不支持.

is a generator expression, which is not supported by numba at the moment.

如果您使用方括号,例如:

If you use square brackets instead, like:

gen = [ind for ind in xrange(len(simple_list)) if simple_list[ind] != number]

那么它是一个列表推导式,numba 可以支持它.有了这个变化,gen 是一个 list,你可以索引它(即 gen[0]).

then it is a list-comprehension and numba can support it. With that change, gen is a list and you can index it (i.e. gen[0]).

以下代码是来自 gitter 用户 sklam 的建议,我在这里更新.

The following code is a suggestion from the user sklam in gitter, that I'm updating here.

@numba.jit(nopython=True)
def the_gen(simple_list, number):
    for ind in range(len(simple_list)):
        if simple_list[ind] != number:
            yield ind


@numba.jit(nopython=True, nogil=True)
def perform_search(simple_list, number):
    for i in the_gen(simple_list, number):
        print(i)

如果您按照上述方式进行操作,您将能够使用生成器(因此可以节省内存和时间),因为 numba 目前不支持生成器表达式.

If you do the above way, you will be able to do with a generator (so gains in memory and time) since generator-expression is currently not supported by numba.