Scala 将元组列表转换为列表元组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27487340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala transform list of tuples to a tuple of lists
提问by Saket
How can I transform a list of tuples List[(A,B)]to a tuple of lists (List[A], List[B])?
如何将元组列表转换为列表元List[(A,B)]组(List[A], List[B])?
I have tried for following but it looks crude and I was hoping there was a better way of doing this
我试过跟随,但它看起来很粗糙,我希望有更好的方法来做到这一点
val flat: List[AnyRef] = aAndB.map{ x =>
x.map(y => List(y._1, y._2))
}.flatMap(x => x)
val typeA: List[A] = flat.filter {
case x: A => true
case _ => false
}.map(_.asInstanceOf[A])
val typeB: List[B] = flat.filter {
case x: B => true
case _ => false
}.map(_.asInstanceOf[B])
回答by Michael Zajac
You want unzip
你要 unzip
scala> List((1,"a"), (3, "b"), (4, "d")).unzip
res1: (List[Int], List[String]) = (List(1, 3, 4),List(a, b, d))
Similarly there is an unzip3for List[Tuple3[A, B, C]], though anything of higher arity you'd have to implement yourself.
同样,有一个unzip3for List[Tuple3[A, B, C]],尽管您必须自己实现任何更高的数量。
scala> List((1,"a", true), (3, "b", false), (4, "d", true)).unzip3
res2: (List[Int], List[String], List[Boolean]) = (List(1, 3, 4),List(a, b, d),List(true, false, true))

