从List中获取前n个元素

时间:2014-07-25 09:04:20

标签: list scala collections scala-collections

我有List

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

我想采用它的前n个元素,但问题是parents大小不固定。

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

3 个答案:

答案 0 :(得分:21)

您可以使用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)

答案 1 :(得分:5)

List(1,2,3).take(100) //List(1,2,3)

take的签名会将参数与index进行比较,因此增量索引永远不会超过参数

拍摄的签名

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
}

答案 2 :(得分:2)

使用take

val familliar = family.take(3)