将清单分成几部分 [英] Divide list into parts
本文介绍了将清单分成几部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Kotlin中,有没有一种简单的方法可以将列表分为几个部分(也许是lambda)?
Is there a simple way to divide list into parts (maybe some lambda) in Kotlin?
例如:
[1, 2, 3, 4, 5, 6] => [[1, 2], [3, 4], [5, 6]]
推荐答案
给出列表:val list = listOf(1, 2, 3, 4, 5, 6)
您可以使用
Given the list: val list = listOf(1, 2, 3, 4, 5, 6)
you can use groupBy
:
list.groupBy { (it + 1) / 2 }.map { it.value }
或者,如果您的值不是数字,则可以先为其分配一个索引:
Or if your values are not numbers you can first assign an index to them:
list.withIndex()
.groupBy { it.index / 2 }
.map { it.value.map { it.value } }
Or if you'd like to save some allocations you can go a bit more manual way with foldIndexed:
list.foldIndexed(ArrayList<ArrayList<Int>>(list.size / 2)) { index, acc, item ->
if (index % 2 == 0) {
acc.add(ArrayList(2))
}
acc.last().add(item)
acc
}
这篇关于将清单分成几部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文