【问题标题】:Get first n elements from List从 List 中获取前 n 个元素
【发布时间】:2014-09-17 02:02:48
【问题描述】:

我有一个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

【问题讨论】:

    标签: list scala collections scala-collections


    【解决方案1】:

    使用take:

    val familliar = family.take(3)
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
        List(1,2,3).take(100) //List(1,2,3)
        

        take 的签名会比较参数和索引,所以增量索引永远不会超过参数

        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
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-09
          • 2021-10-30
          • 2016-04-25
          • 2011-04-12
          • 2020-03-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多