Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 查找列表中不在第二个列表中的元素(在scala中)_List_Scala_Functional Programming - Fatal编程技术网

List 查找列表中不在第二个列表中的元素(在scala中)

List 查找列表中不在第二个列表中的元素(在scala中),list,scala,functional-programming,List,Scala,Functional Programming,假设我有两个列表: val a = List('a', 'b', 'c') val b = List('a', 'b', 'c', 'd') 我想得到不在第一个列表中的元素(在本例中是'd')。我知道我可以用一个循环来实现这一点,但是有没有什么奇特的功能方法可以在一行中快速实现这一点 我一直在看Scala列表API,但只能找到并集和交集(这将分别给我列表('a','b','c','d')和列表('a','b','c'))我认为您可以使用b--a。以下是scala的文档: def -- [B &

假设我有两个列表:

val a = List('a', 'b', 'c')
val b = List('a', 'b', 'c', 'd')
我想得到不在第一个列表中的元素(在本例中是'd')。我知道我可以用一个循环来实现这一点,但是有没有什么奇特的功能方法可以在一行中快速实现这一点


我一直在看Scala列表API,但只能找到并集和交集(这将分别给我列表('a','b','c','d')和列表('a','b','c'))

我认为您可以使用
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
对于不推荐使用的方法,很抱歉,这里是当前的好方法:
list1 filterNot(list2contains)

def过滤器非(p:(A)⇒ 布尔值):

列表[A]选择此列表的所有元素 不满足谓词的列表。 p用于测试元素的谓词。 返回一个由所有 此列表中不包含的元素 满足给定的谓词p。这个 元素的顺序保持不变。 定义类:TraversableLike


您可以为此使用
diff

scala> b diff a
res1: List[Char] = List(d)

如果正在执行
diff
,则可能需要使用
Set

当然,这可以通过多种方式实现。对于像数字和字符串列表这样的平面结构,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

val ans1=对于{x谢谢,这很有效!除了在2.8中,他们显然说它不推荐使用并且将被淘汰:OutputTree.scala:136:method--in class List不推荐使用:使用
list1 filterNot(list2包含)
相反,你甚至复制并粘贴了弃用说明!我的坏!=)别担心,我真的看不到弃用的行,只是复制了整行:)