gpt4 book ai didi

scala - 我可以在 Scala 中将两个以上的列表压缩在一起吗?

转载 作者:行者123 更新时间:2023-12-03 05:01:10 25 4
gpt4 key购买 nike

给定以下 Scala 列表:

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 只能用于组合两个列表,因此我认为您需要以某种方式迭代/减少主列表。毫不奇怪,以下内容不起作用:

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)

有什么建议如何做到这一点吗?我认为我缺少一种非常简单的方法。

更新:我正在寻找一种解决方案,可以采用 N 个列表(每个列表包含 M 个元素)的列表并创建 M 个 TupleN 的列表。

更新2:事实证明,对于我的特定用例来说,拥有一个列表列表而不是一个元组列表更好,所以我接受南瓜的回应。它也是最简单的,因为它使用 native 方法。

最佳答案

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))

供将来引用。

关于scala - 我可以在 Scala 中将两个以上的列表压缩在一起吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1664439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com