从列表中获取随机元素 [英] Get Random Element(s) from a List

查看:103
本文介绍了从列表中获取随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在寻找与Ruby 等效的Elixir。 Array#sample 。可以让我做到的事情:

I'm basically looking for an Elixir equivalent of Ruby's Array#sample. Something that would let me do this:

list = [1,2,3,4,5,6,7]

sample(list)
#=> 4

sample(list, 3)
#=> [6, 2, 5]

我在 Elixir列表文档

推荐答案

更新的答案



如何塞·瓦利姆(JoséValim)在他的答案,在 Elixir 1.1 及更高版本中,您现在可以使用以下方法从中获取随机元素列表:

Updated Answer

As José Valim said in his answer, in Elixir 1.1 and above, you can now use these methods to get random element(s) from a list:

  • Enum.random/1 - For getting single random element
  • Enum.take_random/2 - For getting multiple random elements

示例:

Enum.random(list)                         #=> 4

Enum.take_random(list, 3)                 #=> [3, 9, 1]
Enum.take_random(list, 1)                 #=> [7]

记住要调用:random.seed(: erlang.now)首先!

我仍然找不到做到这一点的正确和神奇方法,但这是我能想到的最好方法:

I'm still unable to find a 'proper' and 'magical' way to do this, but this is the best I could come up:

获取单个随机元素:

list |> Enum.shuffle |> hd
#=> 4

注意:如果列表会出现例外情况为空

要获取多个随机元素:

list |> Enum.shuffle |> Enum.take(3)
#=> [7, 1, 5]

这篇关于从列表中获取随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆