scala 獲取數組中元素
We can access a random element from a list in Scala using the random variable. To use the random variable, we need to import the Random class.
我們可以使用隨機變量從Scala中的列表訪問隨機元素。 要使用隨機變量,我們需要導入Random類。
Importing the Random class,
導入Random類,
import.scala.util.Random
Create a random variable,
創建一個隨機變量,
val random_var = new Random
Accessing random element in list,
訪問列表中的隨機元素,
value = list(random_var.nextInt(list.length))
Let's take an example to get a random element from a list in Scala,
讓我們舉一個例子,從Scala的列表中獲取隨機元素,
import scala.util.Random
object MyClass {
def main(args: Array[String]) {
val list = List(12, 65, 89, 41, 99, 102)
val random = new Random
println("Random value of the list " + list(random.nextInt(list.length)))
}
}
Output
輸出量
RUN 1:
Random value of the list 102RUN2:
Random value of the list 65
Explanation:
說明:
Here, we will find the random value from the list. The code looks a bit more stuffed so let's break the extracting process of random value so that it can be easily understandable.
在這里,我們將從列表中找到隨機值。 該代碼看起來有點塞滿了,所以讓我們中斷隨機值的提取過程,使其易于理解。
list(random.nextInt(list.length))
This will extract a random value from the list. So, what we have done is accessing the random index of the list which is done by random.nextInt(list.length). In this, the nextInt() method of Random class is accessed which takes the limits and returns a random value.
這將從列表中提取一個隨機值。 因此,我們要做的就是訪問由random.nextInt(list.length)完成的列表的隨機索引。 在這種情況下,訪問Random類的nextInt()方法,該方法獲取限制并返回一個隨機值。
翻譯自: https://www.includehelp.com/scala/getting-a-random-element-from-a-list-of-elements-in-scala.aspx
scala 獲取數組中元素