如何从 Scala 元组列表中的元素中获取不同的值



你好,我有一个练习,我试图找到元组第二个元素中不存在的所有数字,并将它们打印在列表中。我有一个工作版本,但它返回重复值,并且没有在列表中返回。我似乎不能在这里使用不同的。 任何人都可以向我解释为什么不能在这里使用不同的以及我需要做什么。 此外,如果有更好的方法来获得练习的答案,那将不胜感激。

object Example{
def main(args: Array[String]): Unit = {
val tupleExercise: List[(Int,Int)] = List(
(1, 3),
(2, 3),
(3, 6),
(5, 6),
(5, 7),
(4, 5),
(4, 8),
(4, 9),
(9, 11)
)
def notExistsInSecond(n: List[(Int, Int)]): Unit = {
var potential =
for (a <- n) {
for (c <- n) 
if(c._1 == a._2) println(a._1)
}
}
println(notExistsInSecond(tupleExercise))
}
}
//expected ouput
// [1, 2, 4]

我不认为有一种(高性能(方法可以在一行中编写它,但你可以这样写:

def notExistsInSecond(n: List[(Int, Int)]): List[Int] = {
val second = n.map(_._2).distinct
n.map(_._1).distinct.filterNot(second.contains)
}

如果您使用HashSet而不是List进行查找,则性能可能会更高:

def notExistsInSecond(n: List[(Int, Int)]): List[Int] = {
val valuesSet = n.map(_._2).toSet
n.map(_._1).distinct.filterNot(valuesSet.contains)
}

这是一种通过输入列表并使用Set来确保不同结果的方法。

def notExistsInSecond(n: List[(Int, Int)]): List[Int] = {
val (s1,s2) = n.foldLeft((Set.empty[Int],Set.empty[Int])){
case ((sa,sb),(a,b)) => (sa+a, sb+b)
}
(s1 diff s2).toList
}

与拉斐尔相同的逻辑,但性能更高。

def notExistsInSecond[A](n: List[(A, A)]): List[A] = {
val seconds = n.iterator.map(_._2).toSet
val (result, _) = n.foldLeft(List.empty[Int] -> Set.empty[Int]) {
case ((result, added), (e, _)) =>
if (!seconds(e) && !added(e))
(e :: result) -> (added + e)
else
result -> added
}
result.reverse // If you do not care about the order you can remove this reverse
}

或者,如果您不关心结果是列表,这将更快:

def notExistsInSecond[A](n: List[(A, A)]): Set[A] = {
val seconds = n.iterator.map(_._2).toSet
n.iterator.collect {
case (e, _) if (!seconds(e)) => e
}.toSet
}

最新更新