【发布时间】:2018-01-02 22:21:26
【问题描述】:
我有一个要减少的映射列表,因为它通常包含名称重复项,但我不能只使用 Enum.uniq 因为我想将计数列相加,例如:
list = [%{count: 4, name: "first"}, %{count: 43, name: "second"},
%{count: 11, name: "third"}, %{count: 11, name: "first"},
%{count: 11, name: "second"}, %{count: 28, name: "second"}]
我得到的结果是这样的:
[%{count: 15, name: "first"}, %{count: 82, name: "second"}, %{count: 11, name: "third"}]
找到这个踏板后:How to map and reduce List of Maps in Elixir
我想出了这样的东西;
all_maps
|> Enum.group_by(&(&1.name))
|> Enum.map(fn {key, value} ->
%{name: key, count: value |> Enum.reduce(fn(x, acc) -> x.count + acc.count end)}
end)
但它只有在有多个同名时才有效,上面的列表会给出这样的结果:
[%{count: 15, name: "first"}, %{count: 82, name: "second"}, %{count: %{count: 11, name: "third"}, name: "third"}]
有时它只有一个,所以我需要在这两种情况下都有效的东西,有什么建议吗?
【问题讨论】:
标签: elixir