将列表细分成列表 [英] Subdivide a list into list of lists
问题描述
我想将列表细分为每个子列表的最大大小列表。例如,给定列表(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))
请注意, I would like to subdivide a list into lists of list with a max size for each sublist. For example, given This is what has already been done: Is there a better, more functional way of doing this? Yes there is, using Note that 这篇关于将列表细分成列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!分组实际上会返回一个
Iterator
,这样您就可以在不进行所有计算的情况下懒惰地遍历集合一次。 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.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)
}
}
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))
grouped
actually returns an Iterator
, so that you can lazily traverse the collection without doing all the computation at once.