将列表拆分为具有固定数量元素的多个列表 [英] Split list into multiple lists with fixed number of elements
本文介绍了将列表拆分为具有固定数量元素的多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将元素列表拆分为最多包含N个项目的列表?
How to split a List of elements into lists with at most N items?
ex:给定一个包含7个元素的列表,创建4个组,而最后一个组可能包含较少的元素.
ex: Given a list with 7 elements, create groups of 4, leaving the last group possibly with less elements.
split(List(1,2,3,4,5,6,"seven"),4)
=> List(List(1,2,3,4), List(5,6,"seven"))
推荐答案
我认为您正在寻找grouped
.它返回一个迭代器,但是您可以将结果转换为列表,
I think you're looking for grouped
. It returns an iterator, but you can convert the result to a list,
scala> List(1,2,3,4,5,6,"seven").grouped(4).toList
res0: List[List[Any]] = List(List(1, 2, 3, 4), List(5, 6, seven))
这篇关于将列表拆分为具有固定数量元素的多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文