39

我有两个清单:

val list1 = List("word1","word2","word2","word3","word1")
val list2 = List("word1","word4")

我想从中删除所有出现的list2元素list1,即我想要

List("word2","word2","word3") <= list1 *minus* list2

我这样做了list1 diff list2 ,这让我List("word2","word2","word3","word1")只删除了第一次出现的“word1”。

我无法将其转换为集合,因为我需要有关重复项的知识(请参阅上面的“word2”)。该怎么办?

4

3 回答 3

74

您可以使用

val unwanted = list2.toSet
list1.filterNot(unwanted)

删除所有项目list2(您不需要了解 中的重复项list2)。

于 2013-04-29T12:01:21.170 回答
10
val list1 = List("word1","word2","word2","word3","word1")
val list2 = List("word1","word4") 
list1 diff list2

这会做到的。

于 2019-10-17T18:14:03.157 回答
9

你可以试试这个:

val list1 = List("word1","word2","word2","word3","word1")
val list2 = List("word1","word4")

println(list1.filterNot(list2.contains(_)))
于 2013-04-29T12:03:18.853 回答