两个列表的所有可能组合 [英] All possible combinations of two lists
本文介绍了两个列表的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于我有两个列表:
val ints = listOf(0, 1, 2)
val strings = listOf("a", "b", "c")
我想要它们元素的所有可能组合
and I want all possible combinations of their elements
0a, 1a, 2a, 0b
等
还有比以下更优雅的方法:
is there a more elegant way than:
ints.forEach { int ->
strings.forEach { string ->
println("$int $string")
}
}
推荐答案
您可以基于flatMap
stdlib函数编写以下扩展函数:
You could write these extension functions based on flatMap
stdlib function:
// Extensions
fun <T, S> Collection<T>.cartesianProduct(other: Iterable<S>): List<Pair<T, S>> {
return cartesianProduct(other, { first, second -> first to second })
}
fun <T, S, V> Collection<T>.cartesianProduct(other: Iterable<S>, transformer: (first: T, second: S) -> V): List<V> {
return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } }
}
// Example
fun main(args: Array<String>) {
val ints = listOf(0, 1, 2)
val strings = listOf("a", "b", "c")
// So you could use extension with creating custom transformer
strings.cartesianProduct(ints) { string, int ->
"$int $string"
}.forEach(::println)
// Or use more generic one
strings.cartesianProduct(ints)
.map { (string, int) ->
"$int $string"
}
.forEach(::println)
}
这篇关于两个列表的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文