Scala中包含将元组转换为列表的任何方法吗? [英] Are there any methods included in Scala to convert tuples to lists?
本文介绍了Scala中包含将元组转换为列表的任何方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的Tuple2
为List[List[String]]
,我希望能够将元组转换为列表,以便随后可以使用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:
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屋!
查看全文