[英]Reduce a List of Map of Tuples
I have the following variable 我有以下变量
val x1 = List((List(('a',1), ('e',1), ('t',1)),"eat"), (List(('a',1), ('e',1), ('t',1)),"ate"))
I want to get a 我想要一个
List(Map -> List)
that will look something like the following. 如下所示。 The idea is to group words b the characters contained in them
想法是将单词b中包含的字符分组
Map(List((a,1), (e,1), (t,1)) -> List(eat, ate))
I have used the following to achieve this however not quite getting it right. 我使用以下方法来实现此目的,但是并没有完全正确。 I have used the following code and get the expected result
我已经使用以下代码并获得了预期的结果
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))
However, I would like to return the obvious type Map[List[(Char, Int)],List[String]]
and not Any
as is returned in my case. 但是,我想返回明显的类型
Map[List[(Char, Int)],List[String]]
而不是我所返回的Any
。 Also, i'm wondering if there is a better of doing the whole thing itself. 另外,我想知道是否有更好的方法来完成整个事情。 Many thanks!
非常感谢!
Try this. 尝试这个。
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))
But, yeah, I think you might want to reconsider your data representation. 但是,是的,我认为您可能需要重新考虑数据表示。 That
List[(List[(Char,Int)], String)]
business is rather cumbersome. List[(List[(Char,Int)], String)]
业务相当麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.