如何在Scala中通过另一个列表拆分列表 [英] How to split a list by another list in Scala

查看:103
本文介绍了如何在Scala中通过另一个列表拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Scala的新手,需要解决我的问题。想象一下,我有这些列表:

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

我的愿望是将列表中的第一个列表拆分为列表2以映射它。
所以结果如下所示:

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

如果我的list2是这样的:

  val list2 = List(4,4,3)
  

$ b> val result = List(List(1,2,3,4),List(5,6,7,8),List(9,10,11))

做这件事的最好方法是什么?

解决方案

可以结合使用 scanLeft splitAt

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

给出: (列表(1,2,3,4,5,6),列表(7,8,9,10,11) ))

简要说明: scanLeft 将元素中的每一块 list1 list1 中的其余元素保存起来。剩余的元素根据下一个块的大小 i 分割,其中 i 是<$ c $的元素C> list2中。最后,所有的剩余部分被 unzip._1 抛弃,并且第一个空的虚拟元素被 tail

请注意,由于列表结构是不可变的&在每一步中存储在元组的第二个组件中的中间结果不会占用任何额外的空间,它们仅仅是对 list1 的尾部的引用。


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)

And my desire is to split the first list in a List of Lists using list2 to map it. So the result would be something like this:

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

If my list2 was like this:

val list2 = List(4,4,3)

The result would then be:

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

What is the best way to do this?

解决方案

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.

这篇关于如何在Scala中通过另一个列表拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆