您可以使用Counter
计算事件的发生次数。你也可以用这样的迭代创建计数器:
>>> from collections import Counter
>>> Counter("asdasdafasdasdasd")
Counter({'a': 6, 's': 5, 'd': 5, 'f': 1})
>>> Counter([1,2,3,2,1,2,2,5])
Counter({2: 4, 1: 2, 3: 1, 5: 1})
答案 0 :(得分:3)
不直接,但您可以使用Enum.reduce/3
Enum.reduce values, %{}, fn(x, acc) ->
Map.update(acc, x, 1, &(&1 + 1))
end
答案 1 :(得分:0)
> "asdasdafasdasdasd" |> String.graphemes |> Enum.reduce(%{}, fn (x, acc) -> Map.update(acc, x, 1, &(&1 + 1)) end)
%{"a" => 6, "d" => 5, "f" => 1, "s" => 5}
> [1,2,3,2,1,2,2,5] |> Enum.reduce(%{}, fn (x, acc) -> Map.update(acc, x, 1, &(&1 + 1)) end)
%{1 => 2, 2 => 4, 3 => 1, 5 => 1}