In Scala, how to get a slice of a list from nth element to the end of the list without knowing the length?

前端 未结 4 749
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-02 05:34

I\'m looking for an elegant way to get a slice of a list from element n onwards without having to specify the length of the list. Lets say we have a multiline string which I spl

相关标签:
4条回答
  • 2021-02-02 06:08

    Just drop first n elements you don't need:

    List(1,2,3,4).drop(2)
    res0: List[Int] = List(3, 4)
    

    or in your case:

    string.split("\n").drop(2)
    

    There is also paired method .take(n) that do the opposite thing, you can think of it as .slice(0,n).

    In case you need both parts, use .splitAt:

    val (left, right) = List(1,2,3,4).splitAt(2)
    left: List[Int] = List(1, 2)
    right: List[Int] = List(3, 4)
    
    0 讨论(0)
  • 2021-02-02 06:21

    You can use scala's list method 'takeRight',This will not throw exception when List's length is not enough, Like this:

    val t = List(1,2,3,4,5);
    t.takeRight(3);
    res1: List[Int] = List(3,4,5)
    

    If list is not longer than you want take, this will not throw Exception:

    val t = List(4,5);
    t.takeRight(3);
    res1: List[Int] = List(4,5)
    
    0 讨论(0)
  • 2021-02-02 06:21

    get last 2 elements:

    List(1,2,3,4,5).reverseIterator.take(2)

    0 讨论(0)
  • 2021-02-02 06:24

    The right answer is takeRight(n):

    "communism is sharing => resource saver".takeRight(3)
                                                  //> res0: String = ver
    
    0 讨论(0)
提交回复
热议问题