使用给定的零件尺寸列表将Scala列表拆分为零件.[分区] [英] Splitting a Scala List into parts using a given list of part sizes.[Partitioning]

查看:83
本文介绍了使用给定的零件尺寸列表将Scala列表拆分为零件.[分区]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

val list1:List[Int]   =  List(5, 2, 6)

val list2:List[Any]  =  List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j","k")

这样list1.sum >= list2.size

我想要一个由list2中的元素连续形成的列表的列表 带有list1中提到的尺寸.

I want a list of lists formed with elements in list2 consecutively with the sizes mentioned in list1.

例如:

如果list1是List(5,2,4),我想要的结果是:

if list1 is List(5,2,4) the result I want is:

List(List("a", "b", "c", "d", "e"),List("f", "g"),List("h", "i", "j","k"))

如果list1是List(5,4,6),我想要的结果是:

if list1 is List(5,4,6) the result I want is:

List(List("a", "b", "c", "d", "e"),List("f", "g","h", "i"),List("j","k"))

如何用简洁的代码做到这一点.

How can I do that with concise code.

推荐答案

list2转换为Iterator,然后映射到list1.

Turn list2 into an Iterator then map over list1.

val itr = list2.iterator
list1.map(itr.take(_).toList)
//res0: List[List[Any]] = List(List(a, b, c, d, e), List(f, g), List(h, i, j, k))


更新: 虽然这似乎可以达到预期的效果,但在其他地方也指出,重用迭代器实际上是不安全的,并且不能保证其行为.


update: While this appears to give the desired results, it has been pointed out elsewhere that reusing the iterator is actually unsafe and its behavior is not guaranteed.

通过一些修改,可以获得更安全的版本.

With some modifications a safer version can be achieved.

val itr = list2.iterator
list1.map(List.fill(_)(if (itr.hasNext) Some(itr.next) else None).flatten)

-或-

import util.Try
val itr = list2.iterator
list1.map(List.fill(_)(Try(itr.next).toOption).flatten)

这篇关于使用给定的零件尺寸列表将Scala列表拆分为零件.[分区]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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