我正在學習Scala。 我想創建一個3人組元組。斯卡拉 - 扁平列表索引製作Tuplets
我的目錄列表
List((B,2), (H,1), (t,1), (S,1))
List((H,1), (t,1), (B,2), (D,1))
期望的結果:扁平化索引(的ListIndex,X,Y)列表...
(1,B,2), (1,H,1), (1,t,1), (1,S,1))
(2,H,1), (2,t,1), (2,B,2), (2,D,1))
我正在學習Scala。 我想創建一個3人組元組。斯卡拉 - 扁平列表索引製作Tuplets
我的目錄列表
List((B,2), (H,1), (t,1), (S,1))
List((H,1), (t,1), (B,2), (D,1))
期望的結果:扁平化索引(的ListIndex,X,Y)列表...
(1,B,2), (1,H,1), (1,t,1), (1,S,1))
(2,H,1), (2,t,1), (2,B,2), (2,D,1))
val input = List(List((B,2), (H,1), (t,1), (S,1)), List((H,1), (t,1), (B,2), (D,1)))
var output = input.zipWithIndex.flatMap({ case (l, i) => l.map(p => (i + 1, p._1, p._2)) })
試試這個:
val list = List(List(("B",2), ("H",1), ("t",1), ("S",1)), List(("H",1), ("t",1), ("B",2), ("D",1)))
val result = list.foldLeft(List[(Int,String,Int)]())((res,sub) => res ++ sub.map(elem => (list.indexOf(sub) + 1,elem._1,elem._2)))
返回result
爲:
List((1,B,2), (1,H,1), (1,t,1), (1,S,1), (2,H,1), (2,t,1), (2,B,2), (2,D,1))
雖然應該有一個更簡單的方法。
scala> val lst = List(
List(('B',2), ('H',1), ('t',1), ('S',1)),
List(('H',1), ('t',1), ('B',2), ('D',1))
)
lst: List[List[(Char, Int)]] = List(List((B,2), (H,1), (t,1), (S,1)), List((H,1), (t,1), (B,2), (D,1)))
scala> lst.flatten.map{ x => (1, x) }
.groupBy{ y => y._2 }
.map{ z => (z._2.length, z._1._1, z._1._2) }
res24: scala.collection.immutable.Iterable[(Int, Char, Int)] =
List((1,D,1), (2,t,1), (2,H,1), (2,B,2), (1,S,1))
生育治療有時會形成連環。 –