电脑做网站,网站首页制作教程,网站设计及建设合同,网站解析多久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中的列表访问随机元素。 要使用随机变量#xff0c;我们需要导入Rand…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 RandomAccessing random element in list, 访问列表中的随机元素 value list(random_var.nextInt(list.length))Lets 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 lets 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.aspxscala 获取数组中元素