mardi 13 mars 2018

How to get random elements from an Elixir map?

I have an Elixir map:

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

What can I use to get random elements from this map?

In Python I can do this:

>>> 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']

Does Elixir have similar tools to extract random elements from a map?




Aucun commentaire:

Enregistrer un commentaire