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 获取数组中元素

    原文作者:cumt30111
    原文地址: https://blog.csdn.net/cumt30111/article/details/107803039
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞