Scala:如何将元组元素转换为列表 [英] Scala: How to convert tuple elements to lists
问题描述
假设我有以下元组列表:
Suppose I have the following list of tuples:
val tuples = listOfStrings.map(string => {
val split = string.split(":")
(split(0), split(1), split(2))
})
我想在一个列表中获取split(0),在另一个列表中获取split(1),依此类推. 可以通过以下方式实现此目的的简单方法:
I would like to get the split(0) in a list, split(1) in another list and so on. A simple way this could be achieved is by writing:
list1 = tuples.map(x => x._1).toList
list2 = tuples.map(x => x._2).toList
list3 = tuples.map(x => x._3).toList
在没有编写3条单独的语句的情况下,是否有一种更优雅(实用)的方法来实现上述目标?
Is there a more elegant (functional) way of achieving the above without writing 3 separate statements?
推荐答案
这将为您提供结果作为列表列表:
This will give you your result as a list of list:
tuples.map{t => List(t._1, t._2, t._3)}.transpose
如果要将它们存储在局部变量中,只需执行以下操作:
If you want to store them in local variables, just do:
val List(l1,l2,l3) = tuples.map{t => List(t._1, t._2, t._3)}.transpose
更新:正如Blaisorblade所指出的那样,标准库实际上为此提供了一个内置方法:unzip3
,它与unzip
一样,但是是三元组而不是成对的:>
UPDATE: As pointed by Blaisorblade, the standard library actually has a built-in method for this: unzip3
, which is just like unzip
but for triples instead of pairs:
val (l1, l2, l3) = tuples.unzip3
不用说,您应该在我上面的手动解决方案中偏爱此方法(但对于Arity元组> 3的情况,仍然适用).
Needless to say, you should favor this method over my hand-rolled solution above (but for tuples of arity > 3, this would still still apply).
这篇关于Scala:如何将元组元素转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!