我可以在 Scala 中将两个以上的列表压缩在一起吗? [英] Can I zip more than two lists together in Scala?
问题描述
给定以下 Scala 列表:
Given the following Scala List:
val l = List(List("a1", "b1", "c1"), List("a2", "b2", "c2"), List("a3", "b3", "c3"))
我如何获得:
List(("a1", "a2", "a3"), ("b1", "b2", "b3"), ("c1", "c2", "c3"))
由于 zip 只能用于组合两个列表,我认为您需要以某种方式迭代/减少主列表.毫不奇怪,以下方法不起作用:
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.
更新:我正在寻找一种解决方案,该解决方案可以采用包含 M 个元素的 N 个列表的列表并创建一个包含 M 个元组的列表.
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.
更新 2: 事实证明,对于我的特定用例来说,最好有一个列表列表,而不是一个元组列表,所以我接受了南瓜的回应.它也是最简单的,因为它使用本机方法.
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.
推荐答案
我不相信生成任意大小的元组列表是可能的,但是 转置函数 如果您不介意获取列表列表,那么它正是您所需要的.
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.
这篇关于我可以在 Scala 中将两个以上的列表压缩在一起吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!