Scala:如何将元组元素转换为列表

编程入门 行业动态 更新时间:2024-10-27 16:23:47
本文介绍了Scala:如何将元组元素转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有以下元组列表:

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:如何将元组元素转换为列表

本文发布于:2023-07-13 03:22:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1099792.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   元素   列表   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!