scala 获取数组中元素_从Scala中的元素列表中获取多个唯一的随机元素

scala 获取数组中元素

在Scala中列出 (List in Scala)

The list is an immutable collection of elements of the same data type. The thing that makes a List different from an array is that List is Linked List.

该列表是相同数据类型的元素的不可变集合。 使List与数组不同的是List是Linked List。

如何获得多个独特元素? (How to get multiple unique elements?)

Multiple random unique elements is a set of elements (more than one) that are random element taken from a unique element of the list randomly.

多个随机唯一元素是一组元素(多个),这些元素是从列表的唯一元素中随机抽取的随机元素。

Example:

例:

    List = (10, 20, 10, 40, 10, 70, 20, 90)
    Distinct elements of list = (10, 20, 40, 70, 90)
    Multiple random elements(2) = (40, 90)

程序查找多个随机唯一元素 (Program to find multiple random unique elements )

object MyObject {
    
    def main(args: Array[String]) {
        val mylist = List(10, 20, 10, 40, 10, 20, 90, 70)
        println("Element of the list:\n" + mylist)
        println("Unique elements of the list:\n" + mylist.distinct)
        println("Multiple Random elmenets of the list:\n" + scala.util.Random.shuffle(mylist.distinct).take(2))
    }
    
}

Output

输出量

Element of the list:
List(10, 20, 10, 40, 10, 20, 90, 70)
Unique elements of the list:
List(10, 20, 40, 90, 70)
Multiple Random elmenets of the list:
List(20, 90)

Explanation:

说明:

In this program, we are going to extract multiple unique random elements from the List. For this we have used 3 function, let's discuss them one by one.

在此程序中,我们将从列表中提取多个唯一的随机元素。 为此,我们使用了3个功能,让我们一一讨论。

  • distinct: the distinct method does exactly what its name suggests i.e. it rips off the duplicate elements and the new list will contain only unique elements.

    与众不同的 :与众不同的方法完全按照其名称的含义进行操作,即,它剔除重复的元素,而新列表将仅包含唯一的元素。

  • shuffle: the shuffle method is a part of Random class the shuffles the elements of the list to a random arrangement.

    shuffle :shuffle方法是Random类的一部分,将列表的元素随机排列为随机排列。

  • take: the take method is used to take any number of elements from the list.

    take :take方法用于从列表中获取任意数量的元素。

So, to extract our multiple unique random elements from the list we have first used the distinct to extract all unique elements. After this, we have shuffled the element using shuffle. so, while taking the element we will get random elements. Finally, we have used to take the method to select 2 elements from the List.

因此,要从列表中提取我们的多个唯一随机元素,我们首先使用了distance来提取所有唯一元素。 之后,我们使用shuffle重组了元素。 因此,在获取元素时,我们将获得随机元素。 最后,我们使用了从列表中选择2个元素的方法。

翻译自: https://www.includehelp.com/scala/getting-multiple-unique-random-elements-from-a-list-of-elements.aspx

scala 获取数组中元素

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值