gpt4 book ai didi

python - 具有嵌套 for 循环、条件和累加器的列表理解

转载 作者:行者123 更新时间:2023-12-04 09:14:49 25 4
gpt4 key购买 nike

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

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)
我尝试了以下建议:
  • List comprehension with an accumulator
  • nested for loops to list comprehension with differents "if" conditions

  • 例如:
    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 , 返回(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成二维阵列形状 (n // d, nb) .缺失的元素(即,循环中的 i + j >= n 的位置)可以为零,因为这将使相应的增量为 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 编译的 vanilla python 编写的任何内容进行对比,它会快得多。

    关于python - 具有嵌套 for 循环、条件和累加器的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63273874/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com