将列表划分为大小为 N 的组

partition list into groups of size-N

获取列表并将其分组为大小为 n 的元组的惯用方法是什么?

例如:用三元组分成 3 个

val list = listOf(1,2,3,4)
val partitioned = list.groupsOf(3)

// partitioned[0] = List<Int> 1, 2, 3
// partitioned[1] = List<Int> 4

但最好是这样的

val list = listOf(1,2,3,4)
val newList = mutableListOf()

list.forGroupsOf(3) { triple: Triple<Int?> ->
    newList.add( triple )
}

// partitioned[0] = Triple<Int?> 1, 2, 3
// partitioned[1] = Triple<Int?> 4, null, null 

注意:List.groupsOfList.forGroupsOf 我弥补了这个例子

Kotlin 提供了一个名为 chunked(n) 的函数,它生成一个列表列表,每个列表包含 n 个元素:

val list = listOf(1, 2, 3, 4)
val tuples = list.chunked(2).map { Tuple(it[0], it[1]) }

或者:

val list = listOf(1, 2, 3, 4)
val tuples = list.chunked(2) { Tuple(it[0], it[1]) }

请记住,这会生成包含 max n 个元素的列表。