Elixir:在元组列表中找到最常见的元素(频率)?
我知道这是 stackoverflow 上的一个常见问题,但找不到专门针对 Elixir 的解决方案。
考虑元组列表:
[
{1, 3, "1S"},
{10, 3, "3S"},
{10, 3, "9S"},
{10, 3, "10S"},
{10, 3, "11S"},
{12, 3, "12S"},
{13, 3, "13S"}
]
预期结果:每个元组的第一个参数中最常见的元素是 10。每个元组的第二个参数中最常见的元素是 3。
是否有执行此操作的函数,或者我必须创建自己的函数来“迭代”每个元组列表elem(list, index)?
回答
You can combine Enum.frequencies_by/2 and Enum.max_by/2 to get the most frequent element:
iex(2)> x |> Enum.frequencies_by(&elem(&1, 0)) |> Enum.max_by(&elem(&1, 1))
{10, 4}
iex(3)> x |> Enum.frequencies_by(&elem(&1, 1)) |> Enum.max_by(&elem(&1, 1))
{3, 7}
iex(4)> x |> Enum.frequencies_by(&elem(&1, 2)) |> Enum.max_by(&elem(&1, 1))
{"10S", 1}
Note that, since frequencies_by returns a map (and maps are unordered), it is undefined which element gets returned by max_by if there is a tie, as you can see in the last example.