我正在学习Scala。 我想创建一个3人的元组。
我有一份清单
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))
答案 0 :(得分:4)
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)) })
答案 1 :(得分:1)
试试这个:
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))
应该有一种更简单的方法。
答案 2 :(得分:0)
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))