将列表映射到以下元素的元组

时间:2018-04-09 20:00:16

标签: kotlin

我已经给出了一个整数列表。我需要在进一步的进展中始终映射两个以下元素。如果输入列表包含无效的元素计数,则应删除最后一个元素。这是一个例子:

[1, 2, 3, 4, 5, 6, 7] //Input
[(1, 2), (3, 4), (5, 6)] //Output

我写了函数来获取想要的输出,但我认为它们效率都很低。

首先,我尝试了一种功能性方法。但它需要两个过滤器调用和一个zip调用结果列表。所以它在内含列表上迭代2.5次。

两个imrpove这个我尝试了迭代方法。它只在列表上迭代一次,可能是最快的版本。但它使用多个可变变量/列表。它也不像功能方法那么容易理解。 (它打破了其余代码的清晰度)

fun main(args: Array<String>) {
    mapFunctional()
    mapIterative()
}

fun mapFunctional() {
    val list: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)

    val output: List<Pair<Int, Int>> = list.filterIndexed { index, _ ->
        index % 2 == 0
    }.zip(list.filterIndexed {
        index, _ -> index % 2 == 1
    })

    println(output)
}

fun mapIterative() {
    val list: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)

    val output: MutableList<Pair<Int, Int>> = mutableListOf()
    var index = 0
    while (index < list.size - 1) {
        output.add(list[index++] to list[index++])
    }

    println(output)
}

他们是一个很好的(有效的)方法,可以通过一个经典的循环来实现这个目标吗?或者它只能用经典的循环来实现吗?

2 个答案:

答案 0 :(得分:3)

如果您需要List<Pair>,则可以使用标准库调用windowed

val myList = listOf(1, 2, 3, 4, 5, 6, 7)
val listOfPairs = myList.windowed(2, 2).map { Pair(it[0], it[1]) }
// [(1, 2), (3, 4), (5, 6)]

windowed函数将返回List<List<Int>>,因此您必须将内部List<Int>映射到Pair<Int, Int>。默认情况下,windowed功能会删除部分窗口。

答案 1 :(得分:0)

您可以使用标准库函数.chunked(n)来实现此目的:

val list = listOf(1, 2, 3, 4, 5, 6, 7)
val output = list.chunked(2).dropLastWhile { it.size < 2 } 

由于chunked保留了包含少于所需尺寸的项目的最后一个部分列表,您需要处理此项并使用.dropLastWhile { ... }

有条件地删除它
相关问题