2013-10-10 120 views
0

我想關鍵結合元組

List((1, 11), (2, 21), (1, 13), (1, 14), (2, 25)) 

到此列表的價值觀結合起來,獲得這樣的名單列表:

List((1, List(11, 13, 14)), (2, List(21, 25))) 

我想使用GROUPBY然後的reduceLeft爲每個元素,但我認爲可能有一個更簡單,更直接的方式?

回答

5
scala> val l = List((1, 11), (2, 21), (1, 13), (1, 14), (2, 25)) 
l: List[(Int, Int)] = List((1,11), (2,21), (1,13), (1,14), (2,25)) 


scala> l.groupBy(_._1).toList.map(xs => (xs._1, xs._2.map(t => t._2))) 
res0: List[(Int, List[Int])] = List((2,List(21, 25)), (1,List(11, 13, 14))) 
2

這類似於@Brians的解決方案,但使用模式匹配:

scala> val xs = List((1, 11), (2, 21), (1, 13), (1, 14), (2, 25)) 
l: List[(Int, Int)] = List((1,11), (2,21), (1,13), (1,14), (2,25)) 

xs.groupBy(_._1).toList.map { case (k, v) => (k, v.map(_._2)) } 
res13: List[(Int, List[Int])] = List((1,List(11, 13, 14)), (2,List(21, 25))) 

如果您沒有問題Map作爲結果類型可以縮短了一點:

xs.groupBy(_._1).map { case (k, v) => (k, v.map(_._2))} 

或:

xs.groupBy(_._1).map { t => (t._1, t._2.map(_._2))}