减少元组映射列表
Reduce a List of Map of Tuples
我有以下变量
val x1 = List((List(('a',1), ('e',1), ('t',1)),"eat"), (List(('a',1), ('e',1), ('t',1)),"ate"))
我想要一个
List(Map -> List)
这将类似于以下内容。这个想法是将单词 b 中包含的字符分组
Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))
我使用了以下方法来实现这一点,但不太正确。我使用了下面的代码并得到了预期的结果
scala> val z1 = x1.groupBy(x => x._1 )
.map(x => Map(x._1 -> x._2.map(z=>z._2)))
.fold(){(a,b) => b}
z1: Any = Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))
但是,我想 return 明显的类型 Map[List[(Char, Int)],List[String]]
而不是 Any
就像 return 在我的例子中那样。另外,我想知道自己做整件事是否更好。非常感谢!
试试这个。
scala> x1.groupBy(_._1).mapValues(_.map(_._2))
res2: scala.collection.immutable.Map[List[(Char, Int)],List[String]] = Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))
但是,是的,我认为您可能需要重新考虑您的数据表示。那List[(List[(Char,Int)], String)]
生意比较麻烦
我有以下变量
val x1 = List((List(('a',1), ('e',1), ('t',1)),"eat"), (List(('a',1), ('e',1), ('t',1)),"ate"))
我想要一个
List(Map -> List)
这将类似于以下内容。这个想法是将单词 b 中包含的字符分组
Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))
我使用了以下方法来实现这一点,但不太正确。我使用了下面的代码并得到了预期的结果
scala> val z1 = x1.groupBy(x => x._1 )
.map(x => Map(x._1 -> x._2.map(z=>z._2)))
.fold(){(a,b) => b}
z1: Any = Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))
但是,我想 return 明显的类型 Map[List[(Char, Int)],List[String]]
而不是 Any
就像 return 在我的例子中那样。另外,我想知道自己做整件事是否更好。非常感谢!
试试这个。
scala> x1.groupBy(_._1).mapValues(_.map(_._2))
res2: scala.collection.immutable.Map[List[(Char, Int)],List[String]] = Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))
但是,是的,我认为您可能需要重新考虑您的数据表示。那List[(List[(Char,Int)], String)]
生意比较麻烦