如何为此for循环创建列表理解

豪尔赫·波萨达

我正在尝试使用列表理解来替换此for循环。我的清单是

test_list = [3, 4, 6, 3, 8, 4, 7, 8, 12, 14, 1, 6, 7, 3, 7, 8, 3, 3, 7]

该功能是

import numpy as np
def ema(x, n):
    x = np.array(x)
    emaint = np.zeros(len(x))
    k = 2 / float(n + 1)

    emaint[0:n] = np.average(x[:n])

    for i in range(n, len(x)):
        emaint[i] = (x[i] * k) + (emaint[i - 1] * (1 - k))

    return emaint

如果我调用ema(test_list,5)的结果将是

[4.8 4.8 4.8 4.8 4.8 4.53333333 5.35555556 6.23703704 8.15802469 10.10534979 7.0702332 6.7134888 6.80899253 5.53932835 6.0262189 6.68414594 5.45609729 4.63739819 5.42493213]

我试过了

import numpy as np
def ema_compr(x, n):
    x = np.array(x)
    emaint = np.zeros(len(x))
    k = 2 / float(n + 1)

    emaint[0:n] = np.average(x[:n])

    emaint[n:] = [(x[i] * k) + (emaint[i - 1] * (1 - k)) for i in range(n, len(x))]

    return emaint

但是,如果我调用ema_compr(test_list,5),结果将有所不同:

[4.8 4.8 4.8 4.8 4.8 4.53333333 2.33333333 2.66666667 4. 4.66666667 0.33333333 2. 2.33333333 1. 2.33333333 2.66666667 1. 1. 2.33333333]
  1. 我想是否有可能获得列表理解。
  2. 列表理解的结果是否因为我要访问未创建的元素而有所不同?
保罗·潘泽

由于您的循环需要保持运行状态,因此尽管存在骇客,但仍无法将其完全转换为列表理解

因此,如果您希望列表理解“类似”,我推荐下一个最好的方法:累加器。

from itertools import accumulate

def ema(x, n):
    xx = n*[sum(x[:n])/n] + x[n:]
    p, q = 2 / (n+1), (n-1) / (n+1)
    return list(accumulate(xx, lambda a, b: q*a + p*b))

给出:

ema(test_list, 5)
# [4.8, 4.8, 4.8, 4.8, 4.8, 4.533333333333333, 5.355555555555555, 6.2370370370370365, 8.158024691358024, 10.105349794238682, 7.070233196159121, 6.713488797439414, 6.808992531626275, 5.539328354417517, 6.026218902945011, 6.684145935296673, 5.456097290197782, 4.637398193465188, 5.424932128976792]

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章