将列表拆分为具有固定数量元素的多个列表

问题描述:

如何将元素列表拆分为最多包含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))