将列表细分成列表 [英] Subdivide a list into list of lists

查看:130
本文介绍了将列表细分成列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表细分为每个子列表的最大大小列表。例如,给定列表(1,2,5,3,90,3,4,1,0,3)和子列表的最大大小定义为4,我会喜欢获得 List(List(1,2,5,3),List(90,3,4,1),List(0,3)) back。



这是已经完成的工作:

  val l:List [Int] = ??? 
val subSize:Int = 4
val rest:Int = if(l.size%subSize == 0)1 else 0

val subdivided:List [List [Int] ] = for {
j < - List.range(0,l.size / subSize - rest,1)
}产生{
for {
i< - List.range (subSize * j,subSize * j + 3,1)
if(i } yield {
l(i)
}
}

是否有更好,更实用的方法?

解决方案

是的,使用分组

 阶> List(1,2,5,3,90,3,4,1,0,3).grouped(4).toList 
res1:List [List [Int]] = List(List(1,2 ,5,3),List(90,3,4,1),List(0,3))

请注意,分组实际上会返回一个 Iterator ,这样您就可以在不进行所有计算的情况下懒惰地遍历集合一次。

I would like to subdivide a list into lists of list with a max size for each sublist. For example, given List(1,2,5,3,90,3,4,1,0,3) and max size of sublists defined as 4, I would like to get List(List(1,2,5,3), List(90,3,4,1), List(0,3)) back.

This is what has already been done:

val l: List[Int] = ???
val subSize: Int = 4
val rest: Int = if(l.size % subSize == 0) 1 else 0

val subdivided: List[List[Int]] = for{
  j <- List.range(0, l.size/subSize - rest, 1)
}yield{
  for{
    i <- List.range(subSize*j,subSize*j+3,1)
    if(i < l.size)
  }yield{
    l(i)
  }
}

Is there a better, more functional way of doing this?

解决方案

Yes there is, using grouped.

scala> List(1,2,5,3,90,3,4,1,0,3).grouped(4).toList
res1: List[List[Int]] = List(List(1, 2, 5, 3), List(90, 3, 4, 1), List(0, 3))

Note that grouped actually returns an Iterator, so that you can lazily traverse the collection without doing all the computation at once.

这篇关于将列表细分成列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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