替换的Python循环迭代

时间:2018-10-20 17:40:31

标签: python python-3.x

我有类似的时间序列数组

[[1539841080000,None],[1539841140000,None],[1539841200000,1.07609359e+08],
 [1539841260000,None],[1539841320000,None],[1539841380000,None],
 [1539841440000,None],[1539841500000,None],[1539841560000,1.07613162e+08],
 [1539841620000,None],[1539841680000,None],[1539841740000,None],
 [1539841800000,None]]

,并希望得到类似的结果

[[1539841200000,1.07609359e+08],[1539841260000,1.07609359e+08],
 [1539841320000,1.07609359e+08],[1539841380000,1.07609359e+08],
 [1539841440000,1.07609359e+08],[1539841500000,1.07609359e+08]]

因此,当第一个值出现在数组中时,也应将其转发到其他数组值,直到下一个值出现为止,而且还必须丢弃具有时间序列的初始空值

我也想从上述时间序列数据中生成增量值。 是否可以从新值-旧值中获得增量[1539841200000,107613162.0-107609359.0],[1539841260000,107613162.0-107609359.0],[1539841320000,107613162.0-107609359.0],[1539841380000,107613162.0-107609359.0],[1539841440000,107613162.0- 107609359.0],[1539841500000、107613162.0-107609359.0],代码中的临时变量数量较少

1 个答案:

答案 0 :(得分:2)

我假设null是指None

data = [[1539841080000,None],[1539841140000,None],[1539841200000,1.07609359e+08],[1539841260000,None],[1539841320000,None],[1539841380000,None],[1539841440000,None],[1539841500000,None],[1539841560000,1.07613162e+08],[1539841620000,None],[1539841680000,1.07613162e+08],[1539841740000,None],[1539841800000,None]]

prev_val = None
new_data = []

for item in data:
    t, d = item
    if d is None and prev_val is not None:
        new_data.append([t,prev_val])
    elif d is not None:
        prev_val = d
        new_data.append(item)

print(new_data)

输出:

[[1539841200000, 107609359.0], [1539841260000, 107609359.0], [1539841320000, 107609359.0], [1539841380000, 107609359.0], [1539841440000, 107609359.0], [1539841500000, 107609359.0], [1539841560000, 107613162.0], [1539841620000, 107613162.0], [1539841680000, 107613162.0], [1539841740000, 107613162.0], [1539841800000, 107613162.0]]