如何查找列表包含来自另一个列表的任何值,并使用scala生成组合列表?

时间:2015-02-06 07:40:18

标签: scala scala-collections

我有以下两个清单 -

list1 = List(("jira","ABC"),
             ("collApp","ABC"),
             ("amarColl","ABC"),
             ("Ubuntu1404","PQR"),
             ("relColAdmin","XYZ"))

list2 = List(("Linux_server","Hyper-V","suseLinux"), 
             ("Linux_server","VmWare","collApp"), 
             ("Linux_server","VmWare","relColAdmin"), 
             ("Linux_server","VmWare","amarColl"),
             ("Linux_server","Hyper-V","ubuntu1310"))

从上面的两个列表我想检查第二个列表是否包含list1的每个元素(元组)的第一个值,如果匹配则在list2中插入第二个值,否则在list2中插入空值。

以下是示例输出 -

output = List(("Linux_server","Hyper-V","suseLinux",""),
              ("Linux_server","VmWare","collApp","ABC"),
              ("Linux_server","VmWare","relColAdmin","XYZ"),
              ("Linux_server","VmWare","amarColl","ABC"),  
              ("Linux_server","Hyper-V","ubuntu1310",""))

3 个答案:

答案 0 :(得分:5)

list1已经处于完美的形式,可以变成地图。我们将其转换为默认值为""的地图。因此,如果我们从地图中请求一个不存在的密钥,我们就会回来""

scala> val map1 = list1.toMap.withDefaultValue("")
map1: scala.collection.immutable.Map[String,String] = 
    Map(amarColl -> ABC, Ubuntu1404 -> PQR, relColAdmin -> XYZ,
        jira -> ABC, collApp -> ABC)

现在我们所要做的就是将3元组映射到4元组:

scala> list2.map { case (a,b,c) => (a,b,c,map1(c)) }
res0: List[(String, String, String, String)] = 
   List((Linux_server,Hyper-V,suseLinux,""),
        (Linux_server,VmWare,collApp,ABC), 
        (Linux_server,VmWare,relColAdmin,XYZ), 
        (Linux_server,VmWare,amarColl,ABC),
        (Linux_server,Hyper-V,ubuntu1310,""))

答案 1 :(得分:1)

如果list1的元组的第一个元素可以放在list2的元组的任何位置,请使用以下代码:

list2.map {
  case (a, b, c) =>
    (a, b, c,
      list1.find(e =>
        Seq(a, b, c).contains(e._1)
      ).map(_._2).getOrElse(""))
}

如果list1的元组的第一个元素只能放在list2的元组的第3个位置:

list2.map {
  case (a, b, c) =>
    (a, b, c,
      list1.find(_._1 == c)
        .map(_._2).getOrElse(""))
}

答案 2 :(得分:0)

首先,将它们拉在一起

val zipped = list1 zip list2 

然后,映射压缩对并构建结果

val output = zipped.map(case ((key, value), targetTuple) => buildResultTuple(key, value, targetTuple))

def buildResultTuple(key:String, value: String, t:Tuple3):Tuple4 = {
   val l = t.productIterator.toList
   if (l contains key) (t._1, t._2, t._3, value)
   else                (t._1, t._2, t._3, "")
}