汇总值的地图列表

时间:2017-05-14 16:43:09

标签: elixir

我有这个:

%{
    1 => 20,
    2 => 8,
    3 => 7
  }

我怎么能得到这个?

Enum.group_by a1, &(&1.id)

  # =>

  %{
    1 => [%{id: 1, val: 12}, %{id: 1, val: 3}, %{id: 1, val: 5}],
    2 => [%{id: 2, val: 3}, %{id: 2, val: 5}],
    3 => [%{id: 3, val: 7}]
  }

即,按“id”

分组的每个项目的“val”之和

我应该先按“id”分组吗?

map

然后在每个项目上执行reduceInvalidArgumentError (see above for traceback): Input to reshape is a tensor with 154587 values, but the requested shape has 150528 ?或者有更好的方法吗?

1 个答案:

答案 0 :(得分:5)

我这样做,只需一次Enum.reduce/3电话:

[%{id: 1, val: 12}, %{id: 3, val: 7}, %{id: 1, val: 5}, %{id: 2, val: 3}, %{id: 2, val: 5}, %{id: 1, val: 3}]
|> Enum.reduce(%{}, fn %{id: id, val: val}, map ->
  Map.update(map, id, val, &(&1 + val))
end)
|> IO.inspect

输出:

%{1 => 20, 2 => 8, 3 => 7}

这应该比group_by + map + reduce更有效。