在列表中查找不在第二个列表中的元素(在 Scala 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3649951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find elements in a list that are not in the second list (in scala)
提问by Enrico Susatyo
Suppose I have two lists:
假设我有两个列表:
val a = List('a', 'b', 'c')
val b = List('a', 'b', 'c', 'd')
I want to get the element which is not in the first list (in this case it's 'd'). I know I can do this with a loop, but is there any fancy functional way to do this quickly in one line?
我想获取不在第一个列表中的元素(在本例中为“d”)。我知道我可以用循环来做到这一点,但是有没有什么奇特的功能方法可以在一行中快速做到这一点?
I've been looking at the Scala List API, but could only found union and intersection (which will give me List('a', 'b', 'c', 'd') and List('a', 'b', 'c') respectively)
我一直在查看 Scala List API,但只能找到并集和交集(这会给我 List('a', 'b', 'c', 'd') 和 List('a', 'b ', 'c') 分别)
采纳答案by vodkhang
I think you can use b -- a. Here is the documentation from scala:
我认为你可以使用b -- a. 以下是 Scala 的文档:
def -- [B >: A] (that: List[B]) : List[B]
Computes the difference between this list and the given list that.
that
the list of elements to remove from this list.
returns this list without the elements of the given list that.
deprecated: use list1 filterNot (list2 contains) instead
Sorry for the deprecated method, here is the current good one: list1 filterNot (list2 contains)
很抱歉弃用的方法,这是当前的好方法: list1 filterNot (list2 contains)
def filterNot (p: (A) ? Boolean) :List[A] Selects all elements of this list which do not satisfy a predicate. p the predicate used to test elements. returns a new list consisting of all elements of this list that do not satisfy the given predicate p. The order of the elements is preserved. definition classes: TraversableLike
def filterNot (p: (A) ? Boolean) :List[A] 选择此列表中不满足谓词的所有元素。p 用于测试元素的谓词。返回一个新列表,该列表包含此列表中不满足给定谓词 p 的所有元素。元素的顺序被保留。定义类:TraversableLike
回答by olle kullberg
You can use difffor this:
您可以diff为此使用:
scala> b diff a
res1: List[Char] = List(d)
You probably want to work with Setif you are doing diff.
你可能想使用的Set,如果你正在做的diff。
回答by Abel Terefe
Of course, this can be done in many ways. For flat structures like list of numbers and strings diffis the most elegant. Other ways are,
当然,这可以通过多种方式完成。对于像数字和字符串列表这样的扁平结构diff是最优雅的。其他方式是,
val ans1 = for { x <- b if !a.contains(x) } yield x
val ans2 = for { x <- b if !a.exists(_ == x) } yield x
val ans3 = b filterNot (x => b.contains(x) )
val ans4 = b diff a

