【发布时间】:2021-12-09 02:35:17
【问题描述】:
假设我有一个整数列表:[2, 4, 4, 6, 1, 8, 3, 5, 2, 2, 2],我想将此列表拆分为子列表,以便每个子列表包含与谓词匹配的值,或者如果不匹配则只有不匹配的值t 匹配,并且应该按照原始列表的顺序。
例如,如果谓词是“偶数”,我希望得到以下结果:
[[2, 4, 4, 6],[1],[8],[3, 5],[2, 2, 2]]
我有一个有效的代码,但在我看来它很丑陋,我觉得应该有更好的方法来编写它:
private fun <T : Any> toSubLists(values: List<T>, predicate: (T) -> Boolean): List<List<T>> {
val subLists = mutableListOf<List<T>>()
var currentList = mutableListOf<T>()
values.forEach {
if (!predicate(it)) {
if (currentList.isNotEmpty()) {
subLists.add(currentList)
currentList = mutableListOf()
}
subLists.add(listOf(it))
} else {
currentList.add(it)
}
}
if (currentList.isNotEmpty()) {
subLists.add(currentList)
}
return subLists
}
【问题讨论】:
-
当谓词为
is negative时,像示例这样的元素如何落在不同的子列表中?所有这些因素都是积极的。 -
@user1984 我猜他的意思是“是偶数”
-
@IvoBeckers 你是对的,
is even签出。 -
但是如果我理解代码和要求,我认为代码实际上应该说
if (!predicate(it))
标签: algorithm kotlin data-structures