在kotlin中,如果我有一对,我可以得到这样的第一个值和第二个值的列表:
val(firstList, secondList) = listOfPairs.unzip()
// listOfPairs: List<Pair<String, Long>>
如何为Triple
做同样的事情?
答案 0 :(得分:1)
如何回弹这样的东西:
fun <X>List<Triple<X,X,X>>.unzip(): List<List<X>> {
return fold(listOf(ArrayList<X>(), ArrayList<X>(), ArrayList<X>())){ r, i ->
r[0].add(i.first)
r[1].add(i.second)
r[2].add(i.third)
r
}
}
用法:
val triplesList = listOf(Triple(1,"s",3), Triple(1,"u",3), Triple(1,"p",3))
val (listOne, listTwo, listThree) = triplesList.unzip()
println("ListOne: $listOne")
println("ListTwo: $listTwo")
println("ListThree: $listThree")
/* Output:
ListOne: [1, 1, 1]
ListTwo: [s, u, p]
ListThree: [3, 3, 3]
*/
答案 1 :(得分:0)
怎么样?
val firstList = listOf(triple1, triple2).map {it.first }
val secondList = listOf(triple1, triple2).map { it.second }
val thirdList = listOf(triple1, triple2).map { it.third }
或
val result = listOf(triple1, triple2).map {
Triple(it.first, it.second, it.third)
}