所以我有以下简单的代码。我想要做的是为给定的 (char , int) 元组列表生成
另一个列表,如示例中所述:
对于 List((a,2),(b,1)),我想要一个列表 List( List((a,1)) ,List((a,2)), List((b,1)) )。
val abba = List(('a', 2), ('b', 2))
abba.map(elt=> for(t<-elt._2) yield (elt,t))
我在以下代码片段上测试了我的方法,但出现以下错误:
错误:(72, 31) value map 不是 Int abba.map(elt=> for(t<-elt._2) yield (elt,t)) 的成员
有关如何解决此问题的任何提示?
如果我正确解释您的要求:
对于 List((a,2),(b,1)),我想要一个列表 List( List((a,1)) ,List((a,2)), List((b,1)) )
您可以使用flatMap
和for/yield
输入生成您的列表列表1 to elt._2
:
val abba = List(('a', 2), ('b', 1))
abba.flatMap( elt => for(t <- 1 to elt._2) yield List((elt._1, t)) )
// res1: List[List[(Char, Int)]] = List(List((a,1)), List((a,2)), List((b,1)))
或者,您可以使用case
部分功能,如下所示:
abba.flatMap{ case (c, i) => for (j <- 1 to i) yield List((c, j)) }
// res2: List[List[(Char, Int)]] = List(List((a,1)), List((a,2)), List((b,1)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句