如何使用scala从元组列表中找出常见元组?

时间:2015-11-19 11:36:42

标签: scala

我有以下两个列表 -

val list1 = List(("192.168.0.1","A"),("192.168.0.2","B"),("192.168.0.3","C"))
val list2 = List(("192.168.0.104",2), ("192.168.0.119",2), ("205.251.0.185",24), ("192.168.0.1",153))

我想匹配两个列表的第一个值,如下所示:

outputList = List(("192.168.0.1","A",153))

目前我正在使用以下来获取输出 -

list1.map{
          ajson =>
            val findHost = list2.filter(_._1.contains(ajson._1.trim))
            if(findHost.nonEmpty) {
              (ajson._1,ajson._2,findHost.head._2)
            } else ("NA","NA",0)
        }.filterNot(p => p._1.equals("NA") || p._2.equals("NA"))

这是正确的做法吗?

我也试过

(list1 ::: list2).groupBy(_._1).map{.......}

但是它给出了list1中的所有元素。

任何人都可以帮助我获得预期的输出吗?

4 个答案:

答案 0 :(得分:5)

你可以试试这个:

def figure_it_out(adding_list):
now = 1
while now == 1:
    added = int(input("Enter the number for the list: "))

    adding_list.append(added)

    if adding_list.count(added) == 2:
        print "already there"
        adding_list.remove(added)
        return adding_list
    else:
        answer = input("Would you like to add another number? (yes or no): ")

        if answer == 'yes':
            now = 1
        elif answer == 'no':
            return adding_list

答案 1 :(得分:3)

可能大多数表现都是

phpstorm

更新

如果您列出的形状比val m1 = list1.toMap val m2 = list2.toMap m1.keySet.intersect(m2.keySet).map(key => (key, m1(key), m2(key))) 更复杂,例如

Tuple2

,您可能需要进行额外的重塑,例如

val list1 = List(("192.168.0.1", "A", true, 'C'), ("192.168.0.2", "B", false, 'D'), ("192.168.0.3", "C", true, 'E'))
val list2 = List(("192.168.0.104", 2, 5.7), ("192.168.0.119", 2, 13.4), ("205.251.0.185", 24, 11.2), ("192.168.0.1", 153, 34.8))

或者您可以使用增强的johny版本进行重新整形:

val m1 = list1.view.map { case (key, v1, v2, v3) => (key, (v1, v2, v3)) }.toMap
val m2 = list2.view.map { case (key, v1, v2) => (key, (v1, v2)) }.toMap

m1.keySet.intersect(m2.keySet).map(key => (key, m1(key), m2(key)))

答案 2 :(得分:1)

以下代码应该可以解决问题

val result = list2.flatMap {
  entry =>
    map.get(entry._1.trim) match {
      case Some(list) =>
        Some(list.map {
          l =>
            (l._1, l._2, entry._2)
        })
      case None => None
    }
}.flatten

答案 3 :(得分:0)

val list2Map = list2.toMap

list1.withFilter(x => list2Map.contains(x._1)).map(s => (s._1, s._2, list2Map(s._1)))