如何从Elixir地图中获取随机元素?

时间:2018-03-13 14:14:08

标签: dictionary random elixir

我有一张Elixir地图:

iex(1)> my_map = %{a: "one", b: "two", c: "three"}
%{a: "one", b: "two", c: "three"}

我可以使用哪些方法从此地图中获取随机元素?

在Python中,我可以这样做:

>>> my_map = {'a': "one", 'b': "two", 'c': "three"}
>>> random.choice(list(my_map.items())) # Get 1 random key-value pair
('a', 'one')
>>> random.sample(my_map.items(), 2) # Get 2 random key-value pairs
[('b', 'two'), ('c', 'three')]
>>> random.choice(list(my_map.keys())) # Get a random key
'b'
>>> random.sample(list(my_map.keys()), 2) # Get 2 random keys
['c', 'a']
>>> random.choice(list(my_map.values())) # Get a random value
'three'
>>> random.sample(list(my_map.values()), 2) # Get 2 random values
['two', 'one']

Elixir是否有类似工具从地图中提取随机元素?

1 个答案:

答案 0 :(得分:1)

获取随机键值对

示例:

iex(1)> my_map = %{a: "one", b: "two", c: "three"}
%{a: "one", b: "two", c: "three"} # Get 1 random key-value pair
iex(2)> Enum.random(my_map)
{:b, "two"}
iex(3)> Enum.take_random(my_map, 2) # Get 2 random key-value pairs
[b: "two", a: "one"]

获取随机密钥

示例:

iex(1)> my_map = %{a: "one", b: "two", c: "three"}
%{a: "one", b: "two", c: "three"}
iex(2)> my_map |> Map.keys() |> Enum.random() # Get 1 random key
:b
iex(3)> my_map |> Map.keys() |> Enum.take_random(2) # Get 2 random keys
[:a, :c]

<强> OR

您可以直接使用Enum.random(enumerable)和一些pattern matching来获取随机密钥:

iex(1)> my_map = %{a: "one", b: "two", c: "three"}
%{a: "one", b: "two", c: "three"}
iex(2)> {key, _} = Enum.random(my_map)
{:c, "three"}
iex(3)> key
:c

获取随机值

示例:

iex(1)> my_map = %{a: "one", b: "two", c: "three"}
%{a: "one", b: "two", c: "three"}
iex(2)> my_map |> Map.values() |> Enum.random() # Get 1 random value
"one"
iex(3)> my_map |> Map.values() |> Enum.take_random(2) # Get 2 random values
["one", "three"]

<强> OR

您可以直接使用Enum.random(enumerable)和一些pattern matching来获取随机值:

iex(1)> my_map = %{a: "one", b: "two", c: "three"}
%{a: "one", b: "two", c: "three"}
iex(2)> {_, value} = Enum.random(my_map)
{:c, "three"}
iex(3)> value
"three"