转换元组列表(并处理重复键?) [英] Convert List of tuple to map (and deal with duplicate key ?)

查看:157
本文介绍了转换元组列表(并处理重复键?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑一个很好的方式来转换一个元组列表,重复键 [(a,b),(c,d),(a ,f)] into map (a - > [b,f],c - > [d]) 。通常(在python中),我会创建一个空的地图,并循环遍历列表,并检查重复的键。但是我正在寻找更多的scala-ish和聪明的解决方案。



btw,这里使用的键值的实际类型是(Int ,Node),我想变成一个(Int - > NodeSeq)的映射

解决方案

组,然后项目:

  scala> val x = List(a - >b,c - >d,a - >f)
// x:List [(java.lang。 String,java.lang.String)] = List((a,b),(c,d),(a,f))
scala> x.groupBy(_._ 1).map {case(k,v)=> (k,v.map(_._ 2))}
// res1:scala.collection.immutable.Map [java.lang.String,List [java.lang.String]] = Map(c - > ;列表(d),a - >列表(b,f))

使用折叠,像那里(跳过地图f step)。


I was thinking about a nice way to convert a List of tuple with duplicate key [("a","b"),("c","d"),("a","f")] into map ("a" -> ["b", "f"], "c" -> ["d"]). Normally (in python), I'd create an empty map and for-loop over the list and check for duplicate key. But I am looking for something more scala-ish and clever solution here.

btw, actual type of key-value I use here is (Int, Node) and I want to turn into a map of (Int -> NodeSeq)

解决方案

Group and then project:

scala> val x = List("a" -> "b", "c" -> "d", "a" -> "f")
//x: List[(java.lang.String, java.lang.String)] = List((a,b), (c,d), (a,f))
scala> x.groupBy(_._1).map { case (k,v) => (k,v.map(_._2))}
//res1: scala.collection.immutable.Map[java.lang.String,List[java.lang.String]] = Map(c -> List(d), a -> List(b, f))

More scalish way to use fold, in the way like there (skip map f step).

这篇关于转换元组列表(并处理重复键?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆