Zip 3等长的列表

时间:2018-04-28 15:43:25

标签: kotlin

Kotlin stdlib中是否有标准操作允许迭代3个(或更多)列表的拉链?

有效地应该这样做:

list1.zip(list2).zip(list3) { (a, b), c -> listOf(a, b, c)}

1 个答案:

答案 0 :(得分:6)

以下是执行此操作的标准库样式中的函数。我并不是说这些都是特别优化的,但我认为它们至少很容易理解。

/**
 * Returns a list of lists, each built from elements of all lists with the same indexes.
 * Output has length of shortest input list.
 */
public inline fun <T> zip(vararg lists: List<T>): List<List<T>> {
    return zip(*lists, transform = { it })
}

/**
 * Returns a list of values built from elements of all lists with same indexes using provided [transform].
 * Output has length of shortest input list.
 */
public inline fun <T, V> zip(vararg lists: List<T>, transform: (List<T>) -> V): List<V> {
    val minSize = lists.map(List<T>::size).min() ?: return emptyList()
    val list = ArrayList<V>(minSize)

    val iterators = lists.map { it.iterator() }
    var i = 0
    while (i < minSize) {
        list.add(transform(iterators.map { it.next() }))
        i++
    }

    return list
}

用法:

val list1 = listOf(1, 2, 3, 4)
val list2 = listOf(5, 6)
val list3 = listOf(7, 8, 9)

println(zip(list1, list2, list3)) // [[1, 5, 7], [2, 6, 8]]