我有Tuple2
List[List[String]]
,我希望能够将元组转换为列表,以便我可以使用List.transpose()
。有没有办法做到这一点?此外,我知道它是Pair
,但我总是喜欢通用解决方案。
答案 0 :(得分:75)
适用于任何元组(scala 2.8):
myTuple.productIterator.toList
Scala 2.7:
(0 to (myTuple.productArity-1)).map(myTuple.productElement(_)).toList
不确定如何维护常规Product或Tuple的类型信息,但是对于Tuple2:
def tuple2ToList[T](t: (T,T)): List[T] = List(t._1, t._2)
当然,您可以为所有元组定义类似的类型安全转换(最多22个)。
答案 1 :(得分:7)
使用无形 -
@ import syntax.std.tuple._
import syntax.std.tuple._
@ (1,2,3).toList
res21: List[Int] = List(1, 2, 3)
@ (1,2,3,4,3,3,3,3,3,3,3).toList
res22: List[Int] = List(1, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3)
请注意,使用Shapeless的toList