【问题标题】:How to reduce List of Maps in Elixir如何减少 Elixir 中的地图列表
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-27
      • 2019-11-22
      • 2023-04-03
      • 2021-01-02
      • 1970-01-01
      • 2021-06-19
      • 2021-06-07
      • 1970-01-01
      相关资源
      最近更新 更多