gpt4 book ai didi

kotlin - zip 3个等长列表

转载 作者:行者123 更新时间:2023-12-01 09:13:55 24 4
gpt4 key购买 nike

Kotlin stdlib中是否有标准操作,该操作可以迭代3个(或更多)列表的zip?

实际上,它应该执行以下操作:

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

最佳答案

这是标准库样式的函数。我并不是说这些是特别优化的,但我认为它们至少很容易理解。

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

关于kotlin - zip 3个等长列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50078266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com