我有这个列表结构列表:
[
["nginx-66b6c48dd5-25wv5", "nginx-deployment", "worker-1", "0", "2"],
["nginx-66b6c48dd5-2nhbs", "nginx-deployment", "worker-1", "0", "2"],
["nginx-66b6c48dd5-5b4dw", "nginx-deployment", "worker-1", "0", "2"],
["nginx-66b6c48dd5-p7sx9", "nginx-deployment", "worker-1", "0", "2"],
["coredns-autoscaler-76f8869cc9-gd69j", "kube-system", "worker-1", "1", "5"],
["coredns-55b58f978-q2skn", "kube-system", "worker-1", "7", "11"]
]
Run Code Online (Sandbox Code Playgroud)
我想通过第二个列表项(nginx-deployment、kube-system 等)合并它们,并将两个最新的项目相加并删除第一个项目。
所以它看起来像这样:
[
["nginx-deployment", "worker-1", "0", "8"],
["kube-system", "worker-1", "8", "16"]
]
Run Code Online (Sandbox Code Playgroud)
Enum.zip 有点工作,但我必须首先拆分子列表,我认为必须有更好的方法来做到这一点。
我会使用Enum.reduce这个,在这个过程中将列表转换为地图。
这个想法是在列表上“循环”,每次用总和更新“累加器”映射,如下所示:
[
["nginx-66b6c48dd5-25wv5", "nginx-deployment", "worker-1", "0", "2"],
["nginx-66b6c48dd5-2nhbs", "nginx-deployment", "worker-1", "0", "2"],
["nginx-66b6c48dd5-5b4dw", "nginx-deployment", "worker-1", "0", "2"],
["nginx-66b6c48dd5-p7sx9", "nginx-deployment", "worker-1", "0", "2"],
["coredns-autoscaler-76f8869cc9-gd69j", "kube-system", "worker-1", "1", "5"],
["coredns-55b58f978-q2skn", "kube-system", "worker-1", "7", "11"]
]
|> Enum.reduce(%{}, fn [_, key, _, stat0, stat1], accumulator ->
int0 = String.to_integer(stat0)
int1 = String.to_integer(stat1)
Map.update(accumulator, key, {int0, int1}, fn {x, y} -> {x + int0, y + int1} end)
end)
Run Code Online (Sandbox Code Playgroud)
那将返回:
%{"kube-system" => {8, 16}, "nginx-deployment" => {0, 8}}
Run Code Online (Sandbox Code Playgroud)
注意:我没有包括“第三个”字段,因为我不确定应该如何选择它。它总是独一无二的吗?无论如何,我的回答概述了我将如何处理这个问题。