Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 如何将列表分块到特定值?[科特林]_List_Kotlin_Chunked_Windowed - Fatal编程技术网

List 如何将列表分块到特定值?[科特林]

List 如何将列表分块到特定值?[科特林],list,kotlin,chunked,windowed,List,Kotlin,Chunked,Windowed,如何将列表分块到特定值? 例如:当前值为5的拆分 将x转换为: x => [[1,2,3,4,5],[2,3,1,5],[4,1,5]] 令人惊讶的是,在标准库中没有这样做的方法。但自己编写一个也不难,例如: /** * Splits a collection into sublists, following each occurrence of the given separator. */ fun <T> Collection<T>.splitAfter(

如何将列表分块到特定值?

例如:当前值为5的拆分

将x转换为:

x => [[1,2,3,4,5],[2,3,1,5],[4,1,5]]

令人惊讶的是,在标准库中没有这样做的方法。但自己编写一个也不难,例如:

/**
 * Splits a collection into sublists, following each occurrence of the given separator.
 */
fun <T> Collection<T>.splitAfter(separator: T): List<List<T>> {
    val result = mutableListOf<MutableList<T>>()
    
    var newSublist = true
    for (item in this) {
        if (newSublist)
            result += mutableListOf<T>()
        result.last() += item
        newSublist = (item == separator)
    }
    
    return result
}
它还处理所有角落情况:空列表、连续分隔符以及零个或多个前导和/或尾随分隔符,例如:

val x = listOf(5, 5, 4, 5, 5, 2)
println(x.splitAfter(5)) // prints [[5], [5], [4, 5], [5], [2]]

(当然,最好包含涵盖所有此类情况的单元测试。)

您是希望将列表拆分为正好包含5个项目的块,还是希望将其拆分为每个块中的最后一个项目为
5
?  (不幸的是,您的示例是两种情况都给出相同结果的极少数情况之一。)第二种情况,我想在特定的“5”值处分块
val x = listOf(1, 2, 3, 4, 5, 2, 3, 1, 5, 4, 1, 5)
println(x.splitAfter(5)) // prints [[1, 2, 3, 4, 5], [2, 3, 1, 5], [4, 1, 5]]
val x = listOf(5, 5, 4, 5, 5, 2)
println(x.splitAfter(5)) // prints [[5], [5], [4, 5], [5], [2]]