Kotlin用前面两个索引中的一个来压缩每个元素



我有一个包含(e1, e2, e3, e4, e5...)的列表。我想将e1e3压缩,将e2e4压缩,依此类推。

我找不到一个zip方法,可以让你选择用当前元素压缩哪个元素。

items.map { item -> item.zipWithNext() } 
[e1, e2, e3, e4, e5, e6, e7, e8] -> [(e1, e3), (e2, e4), (e5, e7), (e6, e8)]

items.zipWithNext()函数本质上是items.zip(items.drop(1))的优化版本。

由于您需要将每个项目与两个位置之间的项目进行压缩,因此您可以使用items.zip(items.drop(2)):

val items = listOf("e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8")
println(items.zip(items.drop(2)))
// prints: [(e1, e3), (e2, e4), (e3, e5), (e4, e6), (e5, e7), (e6, e8)]

对于此要求,列表的大小必须是4的倍数,如下所示:

val list = mutableListOf("e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8")

因此,您可以首先交换位置12569以及10中的项目,依此类推:

for (i in 0..list.size / 4 - 1) 
list[4 * i + 1] = list[4 * i + 2].also { list[4 * i + 2] = list[4 * i + 1] }

现在的列表是:

[e1, e3, e2, e4, e5, e7, e6, e8]

最后使用chunked(2)将列表拆分为两个连续项目的列表:

val newList = list.chunked(2)
println(newList)

将打印:

[[e1, e3], [e2, e4], [e5, e7], [e6, e8]]

如果您的初始列表是不可变的,或者您希望它保持不变,那么创建一个新的可变列表并对其进行操作:

val originalList = listOf("e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8")
val list = originalList.toMutableList()

您应该做一堆工作。

val items = listOf("e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8")
val partitionedItems = items.withIndex().partition { (index, _) -> index % 2 == 0 }
val oddList = partitionedItems.first.map { it.value }
val evenList = partitionedItems.second.map { it.value }

这里有这样的奇数和偶数列表:

[e1,e3,e5,e7]

[e2,e4,e6,e8]

next执行zipWithNext((

oddList.zipWithNext()

这会创建类似于的数据

[(e1,e3(,(e3,e5(,(e5,e7(]

但我们不需要这个项目:

(e3,e5(

因此我们应该过滤它。

val oddListPair = oddList.zipWithNext().withIndex().filter { (index, _) -> index % 2 == 0 }.map { it.value }

我们终于有了

[(e1,e3(,(e5,e7(]

在最后一步中,我们应该合并两个奇数和偶数列表。

oddListPair.zip(evenListPair){ a,b -> listOf(a,b)}.flatten()

完整的代码是这样的。

val items = listOf("e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8")
val partitionedItems = items.withIndex().partition { (index, _) -> index % 2 == 0 }
val oddList = partitionedItems.first.map { it.value } 
val evenList = partitionedItems.second.map { it.value }
val oddListPair = oddList.zipWithNext().withIndex().filter { (index, _) -> index % 2 == 0 }.map { it.value }
val evenListPair = evenList.zipWithNext().withIndex().filter { (index, _) -> index % 2 == 0 }.map { it.value }
oddListPair.zip(evenListPair){ a,b -> listOf(a,b)}.flatten()

最新更新