嵌套,循环和条件累加的列表理解

N. Dryas:

我正在尝试将这段代码转换为列表理解:

a = np.random.rand(10) #input vector
n = len(a) # element count of input vector
b = np.random.rand(3) #coefficient vector
nb = len(b) #element count of coefficients
d = nb #decimation factor (could be any integer < len(a))
 
c = []
for i in range(0, n, d):
    psum = 0
    for j in range(nb):
        if i + j < n:
            psum += a[i + j]*b[j]
    c.append(psum)

我尝试了以下建议:

例如:

from itertools import accumulate
c = [accumulate([a[i + j] * b[j] for j in range(nb) if i + j < n] ) for i in range(0, n, d)]

稍后,当尝试从c(例如c[:index]获取值时

TypeError: 'NoneType' object is not subscriptable

要么:

from functools import partial
def get_val(a, b, i, j, n):
    if i + j < n:
        return(a[i + j] * b[j])
    else:
        return(0)
c = [
         list(map(partial(get_val, i=i, j=j, n=n), a, b)) 
             for i in range(0, n, d) 
             for j in range(nb)
    ]

get_val,return(a [i + j] * b [j])

IndexError: invalid index to scalar variable.

要么:

psum_pieces = [[a[i + j] * b[j] if i + j < n else 0 for j in range(nb)] for i in range(0, n, d)]
c = [sum(psum) for psum in psum_pieces]

以及这些方法的许多其他迭代。任何指导将不胜感激。

疯狂物理学家:

您真的不需要在这里使用列表理解。使用numpy,您可以创建不直接在解释器中运行任何循环的快速流水线解决方案。

首先转换a成2D形状的数组(n // d, nb)缺少的元素(即i + j >= n循环中的where )可以为零,因为这会使相应的增量psum为零:

# pre-compute i+j as a 2D array
indices = np.arange(nb) + np.arange(0, n, d)[:, None]
# we only want valid locations
mask = indices < n

t = np.zeros(indices.shape)
t[mask] = a[indices[mask]]

现在您可以c直接计算

(t * b).sum(axis=1)

我怀疑如果您将此解决方案与未使用numba编译的用python编写的任何东西进行基准测试,它将更快。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章