组合列表中的元组元素

时间:2017-12-15 06:11:37

标签: list tuples elixir

在elixir中工作,我有一个列表,我想减少到唯一的键,将列表元素合并在一起:

[{"abc", [%{a: "a"}]},{"bcd", [%{a: "a"}]},{"bcd", [%{a: "b"}]}]

任何人都可以想到一种简洁的方法来组合元素来达到

[{"abc", [%{a: "a"}]}, {"bcd", [%{a: "a"}, %{a: "b"}]}]

1 个答案:

答案 0 :(得分:4)

Enum.group_by/3来救援:

▶ list = [{"abc", [%{a: "a"}]},{"bcd", [%{a: "a"}]},{"bcd", [%{a: "b"}]}]
▶ list |> Enum.group_by(fn {k, _} -> k end, fn {_, [v]} -> v end)
#⇒ %{"abc" => [%{a: "a"}], "bcd" => [%{a: "a"}, %{a: "b"}]}

如果你坚持最后有一个元组列表,只需将Enum.into/2附加到链中:

|> Enum.into([])
#⇒ [{"abc", [%{a: "a"}]}, {"bcd", [%{a: "a"}, %{a: "b"}]}]

适用于任何大小的值列表的通用解决方案:

▶ list
▷ |> Enum.group_by(fn {k, _} -> k end, fn {_, v} -> v end)
▷ |> Enum.map(fn {k, v} -> {k, List.flatten(v)} end)
#⇒ [{"abc", [%{a: "a"}]}, {"bcd", [%{a: "a"}, %{a: "b"}]}]