Frage

I am learning Scala. I wanna create a 3-members Tuples.

I have a list of list

List((B,2), (H,1), (t,1), (S,1))
List((H,1), (t,1), (B,2), (D,1))

The desired results : flatten list with index (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))

Keine korrekte Lösung

Andere Tipps

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)) })

Try this:

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)))

This returns result as:

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))

There should be a simpler way though.

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))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top