我有一个像(String,(String,Double))这样的嵌套元组结构,我想把它转换成(String,String,Double)。我有各种各样的嵌套元组,我不想手动转换每个元组。有什么方便的方法可以做到这一点?
发布于 2012-12-04 17:17:27
Tupple上没有展平。但是如果你知道它的结构,你可以这样做:
implicit def flatten1[A, B, C](t: ((A, B), C)): (A, B, C) = (t._1._1, t._1._2, t._2)
implicit def flatten2[A, B, C](t: (A, (B, C))): (A, B, C) = (t._1, t._2._1, t._2._2)这将展平任何类型的Tupple。还可以将implicit关键字添加到定义中。这只适用于三个元素。可以展平Tupple,如下所示:
(1, ("hello", 42.0)) => (1, "hello", 42.0)
(("test", 3.7f), "hi") => ("test", 3.7f, "hi")多个嵌套的Tupple不能展平到地面,因为在返回类型中只有三个元素:
((1, (2, 3)),4) => (1, (2, 3), 4)发布于 2018-04-19 17:31:25
不确定这样做的效率,但您可以使用tuple.productIterator.toList将Tuple转换为List,然后flatten嵌套列表:
scala> val tuple = ("top", ("nested", 42.0))
tuple: (String, (String, Double)) = (top,(nested,42.0))
scala> tuple.productIterator.map({
| case (item: Product) => item.productIterator.toList
| case (item: Any) => List(item)
| }).toList.flatten
res0: List[Any] = List(top, nested, 42.0)https://stackoverflow.com/questions/13699070
复制相似问题