【问题标题】:Zip 3 lists of equal lengthZip 3 等长列表
【发布时间】:2018-04-28 15:43:24
【问题描述】:

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

实际上应该这样做:

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

【问题讨论】:

  • 不,没有。
  • 可能不完全符合您的要求,但有 mapIndexed 函数:kotlinlang.org/docs/collection-transformations.html。当要压缩的列表数量变大时,嵌套压缩将导致嵌套对,并且使用所有括号可能难以阅读。但是使用mapIndexed,就不会出现这种嵌套问题。

标签: kotlin


【解决方案1】:

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

/**
 * 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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2021-07-22
    • 2020-09-29
    • 2020-12-23
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多