查找不在第二个列表中的元素(在scala中) [英] Find elements in a list that's not in the second list (in scala)

查看:77
本文介绍了查找不在第二个列表中的元素(在scala中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个列表:

Suppose I have two lists:

val a = List('a', 'b', 'c')
val b = List('a', 'b', 'c', 'd')

我想获取不在第一个列表中的元素(在本例中为'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?

我一直在寻找Scala List API ,但只能找到联合和交集(这将分别给我列表('a','b','c','d')和列表('a','b','c')) p>

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)

推荐答案

我认为您可以使用 b - a 。这里是scala的文档:

I think you can use b -- a. Here is the documentation from 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(list2 contains)

Sorry for the deprecated method, here is the current good one: list1 filterNot (list2 contains)


def filterNot(p:(A)⇒布尔值):

列表[A]选择此
的所有元素不满足谓词的列表。
p用于测试元素的谓词。
返回一个新列表,该列表包含此列表中所有
元素,而不是
满足给定的谓词p。元素的
顺序被保留。
定义类:TraversableLike

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

这篇关于查找不在第二个列表中的元素(在scala中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆