Scala 中是否包含任何将元组转换为列表的方法? [英] Are there any methods included in Scala to convert tuples to lists?

查看:24
本文介绍了Scala 中是否包含任何将元组转换为列表的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List[List[String]]Tuple2 并且我希望能够将元组转换为列表,以便我可以使用List.transpose().有没有办法做到这一点?另外,我知道这是一个 Pair,尽管我一直是通用解决方案的粉丝.

I have a Tuple2 of List[List[String]] and I'd like to be able to convert the tuple to a list so that I can then use List.transpose(). Is there any way to do this? Also, I know it's a Pair, though I'm always a fan of generic solutions.

推荐答案

适用于任何元组(scala 2.8):

Works with any tuple (scala 2.8):

myTuple.productIterator.toList

Scala 2.7:

(0 to (myTuple.productArity-1)).map(myTuple.productElement(_)).toList

<小时>

不确定如何维护一般 Product 或 Tuple 的类型信息,但对于 Tuple2:


Not sure how to maintain type info for a general Product or Tuple, but for Tuple2:

def tuple2ToList[T](t: (T,T)): List[T] = List(t._1, t._2)

当然,您可以为所有元组(最多 22 个)定义类似的类型安全转换.

You could, of course, define similar type-safe conversions for all the Tuples (up to 22).

这篇关于Scala 中是否包含任何将元组转换为列表的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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