Can I zip more than two lists together in Scala?
Solution 1
I don't believe it's possible to generate a list of tuples of arbitrary size, but the transpose function does exactly what you need if you don't mind getting a list of lists instead.
Solution 2
scala> (List(1,2,3),List(4,5,6),List(7,8,9)).zipped.toList
res0: List[(Int, Int, Int)] = List((1,4,7), (2,5,8), (3,6,9))
For future reference.
Solution 3
So this piece of code won't answer the needs of the OP, and not only because this is a four year old thread, but it does answer the title question, and perhaps someone may even find it useful.
To zip 3 collections:
as zip bs zip cs map {
case ((a,b), c) => (a,b,c)
}
Solution 4
Yes, with zip3.
Solution 5
transpose
does the trick. A possible algorithm is:
def combineLists[A](ss:List[A]*) = {
val sa = ss.reverse;
(sa.head.map(List(_)) /: sa.tail)(_.zip(_).map(p=>p._2 :: p._1))
}
For example:
combineLists(List(1, 2, 3), List(10,20), List(100, 200, 300))
// => List[List[Int]] = List(List(1, 10, 100), List(2, 20, 200))
The answer is truncated to the size of the shortest list in the input.
combineLists(List(1, 2, 3), List(10,20))
// => List[List[Int]] = List(List(1, 10), List(2, 20))
pr1001
Updated on July 08, 2022Comments
-
pr1001 almost 2 years
Given the following Scala List:
val l = List(List("a1", "b1", "c1"), List("a2", "b2", "c2"), List("a3", "b3", "c3"))
How can I get:
List(("a1", "a2", "a3"), ("b1", "b2", "b3"), ("c1", "c2", "c3"))
Since zip can only be used to combine two Lists, I think you would need to iterate/reduce the main List somehow. Not surprisingly, the following doesn't work:
scala> l reduceLeft ((a, b) => a zip b) <console>:6: error: type mismatch; found : List[(String, String)] required: List[String] l reduceLeft ((a, b) => a zip b)
Any suggestions one how to do this? I think I'm missing a very simple way to do it.
Update: I'm looking for a solution that can take a List of N Lists with M elements each and create a List of M TupleNs.
Update 2: As it turns out it is better for my specific use-case to have a list of lists, rather than a list of tuples, so I am accepting pumpkin's response. It is also the simplest, as it uses a native method.