How can I transform a list of tuples List[(A,B)]
to a tuple of lists (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])
length match { case 2 => toTuple2 case 3 => toTuple3 } def toTuple2 = elements match {case Seq(a, b) => (a, b) } def toTuple3 = elements match {case Seq(a, b, c) => (a, b, c) } } val product = List(1, 2, 3). toTuple product. productElement(5) //runtime IndexOutOfBoundException, Bad ! val tuple = List(1, 2, 3).
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.
Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed).
You want 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 unzip3
for List[Tuple3[A, B, C]]
, though anything of higher arity you'd have to implement yourself.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With