简体   繁体   English

从List中获取前n个元素

[英]Get first n elements from List

I have a List 我有一个List

val family=List("1","2","11","12","21","22","31","33","41","44","51","55")

i want to take its first n elements but the problem is that parents size is not fixed. 我想采取它的前n个元素,但问题是parents大小不固定。

val familliar=List("1","2","11") //n=3

You can use take 你可以使用take

scala> val list = List(1,2,3,4,5,6,7,8,9)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> list.take(3)
res0: List[Int] = List(1, 2, 3)
List(1,2,3).take(100) //List(1,2,3)

The signature of take will compare the argument with index, so the incremental index will never more than argument take的签名会将参数与index进行比较,因此增量索引永远不会超过参数

The signature of take 采取的签名

override def take(n: Int): List[A] = {
  val b = new ListBuffer[A]
  var i = 0
  var these = this
  while (!these.isEmpty && i < n) {
    i += 1
    b += these.head
    these = these.tail
  }
  if (these.isEmpty) this
  else b.toList
}

使用take

val familliar = family.take(3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM