如何减少Elixir中的地图列表

如何减少Elixir中的地图列表,elixir,Elixir,我有一个要减少的映射列表,因为它通常包含重复的名称,但我不能只使用Enum.uniq,因为我想将count列相加,例如: 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"}] 之后的

我有一个要减少的映射列表,因为它通常包含重复的名称,但我不能只使用Enum.uniq,因为我想将count列相加,例如:

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"}]
找到此踏板后:

我想出了这样的办法

  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"}]

有时这只是一个,所以我需要在这两种情况下都有效的东西,有什么提示吗

问题在于
Enum.reduce/3
。当列表只有一个值时,它将返回该值。我宁愿这样做:

%{name: key, count: value |> Enum.map(& &1.count) |> Enum.sum()}