How to split a list by another list in Scala

后端 未结 3 1561
清酒与你
清酒与你 2021-01-16 06:10

I am new to Scala and I need a solution to my problem. Imagine I have these lists:

val list1 = List(1,2,3,4,5,6,7,8,9,10,11)
val list2 = List(6,5)

3条回答
  •  鱼传尺愫
    2021-01-16 06:40

    You can use a combination of scanLeft and splitAt:

    list2.scanLeft((List.empty[Int], list1)) { 
      case ((_, remaining), i) =>  remaining.splitAt(i)
    }.unzip._1.tail
    

    Gives:

    List(List(1, 2, 3, 4, 5, 6), List(7, 8, 9, 10, 11))
    

    Brief explanation: each step of scanLeft saves each piece of list1 and the remaining elements of list1 in a tuple. The remaining elements are split according to the size i of next chunk, where i is an element of list2. In the end, all the "remainders" are thrown away by unzip._1, and the first empty dummy-element is removed by tail.

    Note that since the list structure is immutable & persistent, the intermediate results stored in the second component of the tuple in each step do not take up any extra space, they are mere references to tails of list1.

提交回复
热议问题