【发布时间】:2020-09-11 08:34:30
【问题描述】:
你好,我有这个练习,我试图找到元组的第二个元素中不存在的所有数字,并将它们打印在一个列表中。我有一个工作版本,但它返回重复值,并且没有在列表中返回。我似乎不能在这里使用 distinct 。谁能向我解释为什么这里不能使用 distinct 以及我需要做什么。此外,如果有更好的方法来获得练习的答案,我们将不胜感激。
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]
【问题讨论】:
-
您能添加预期的输出吗?您要返回第二个元组值中不存在的元组,还是只返回第一个元组值的值?
-
你不能使用
.distinct,因为没有什么可以使用的。您正在打印结果而不是保存它们。最后一行,println(notExists...只打印一个空的\n,因为notExistsInSecond()返回Unit。如果您将结果保存在List中,那么您可以申请.distinct。 -
@RayanRal 我已经更新了预期的输出
-
@jwvh 我不确定如何将结果保存到列表中,你能展示一下实现吗?
标签: scala loops tuples scala-collections