list Scala 中是否包含任何将元组转换为列表的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1919009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are there any methods included in Scala to convert tuples to lists?
提问by pr1001
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.
我有一个Tuple2
,List[List[String]]
我希望能够将元组转换为列表,以便我可以使用List.transpose()
. 有没有办法做到这一点?此外,我知道这是一个Pair
,尽管我一直是通用解决方案的粉丝。
回答by Mitch Blevins
Works with any tuple (scala 2.8):
适用于任何元组(scala 2.8):
myTuple.productIterator.toList
Scala 2.7:
斯卡拉 2.7:
(0 to (myTuple.productArity-1)).map(myTuple.productElement(_)).toList
Not sure how to maintain type info for a general Product or Tuple, but for Tuple2:
不确定如何维护一般产品或元组的类型信息,但对于 Tuple2:
def tuple2ToList[T](t: (T,T)): List[T] = List(t._1, t._2)
You could, of course, define similar type-safe conversions for all the Tuples (up to 22).
当然,您可以为所有元组(最多 22 个)定义类似的类型安全转换。
回答by Michael T
Using Shapeless -
使用无形 -
@ import syntax.std.tuple._
import syntax.std.tuple._
@ (1,2,3).toList
res21: List[Int] = List(1, 2, 3)
@ (1,2,3,4,3,3,3,3,3,3,3).toList
res22: List[Int] = List(1, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3)
Note that type information is not lost using Shapeless's toList
.
请注意,使用 Shapeless 的toList
.