gpt4 book ai didi

jq - jq 中的累计和

转载 作者:行者123 更新时间:2023-12-02 00:59:38 27 4
gpt4 key购买 nike

我在数组中有一系列 [timestamp, count] 对,我想使用 jq 计算每个时间戳的累积和。我怎么能那样做?

这里是一个示例数据集:

[
[1431047957699, 1],
[1431047958269, 1],
[1431047958901, 1],
[1431047959147, -1],
[1431047960164, 1]
]

以及预期的结果:

[1431047957699, 1],
[1431047958269, 2],
[1431047958901, 3],
[1431047959147, 2],
[1431047960164, 3]

是否可以用 jq 做到这一点?

最佳答案

以下是非常通用的(例如,它可以与对象数组一起使用):

def accumulate(f):
reduce .[1:][] as $row
([.[0]];
. as $x
| $x + [ $row | (f = ($x | .[length-1] | f) + ($row|f) ) ] );

accumulate(.[1])

如果您使用的是足够新的 jq 版本,那么“$x | .[length-1]”可以简化为“$x[-1]”。

使用foreach的解决方案

如果你的jq有foreach,那么可以使用下面的变体。如果需要值流而不是数组,这将特别合适。

def accumulates(f):
foreach .[] as $row
(0;
. + ($row | f) ;
. as $x | $row | (f = $x));

用法:

对于流:accumulates(.[0])

对于数组:[accumulates(.[0])

关于jq - jq 中的累计和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30172253/

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