我可以在Scala中压缩两个以上的列表吗? [英] Can I zip more than two lists together in Scala?

查看:81
本文介绍了我可以在Scala中压缩两个以上的列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  val l = List(List(a1,b1,c1 ),列表(a2,b2,c2),列表(a3,b3,c3))

我怎样才能得到:

  List((a1,a2 ,a3),(b1,b2,b3),(c1,c2,c3))

由于zip只能用于组合两个列表,我认为您需要以某种方式迭代/减少主列表。毫不奇怪,以下内容不起作用:

  scala> l reduceLeft((a,b)=> a b)b)
< console>:6:error:type mismatch;
found:List [(String,String)]
required:List [String]
l reduceLeft((a,b)=> a zip b)

任何建议一个如何做到这一点?我认为我错过了一个很简单的方法。



更新:我正在寻找一个可以接受List的N列表中包含M个元素,并创建一个M TupleNs列表。



更新2:事实证明,用例有一个列表列表,而不是一个元组列表,所以我接受南瓜的回应。它也是最简单的,因为它使用本地方法。

解决方案

我不相信有可能生成一个列表任意大小的元组,但转置功能完全符合您的需求,如果您不介意取得列表清单。


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.

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆