list 两个列表的Scala差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16278098/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 02:00:12  来源:igfitidea点击:

Scala difference of two lists

listscala

提问by Pavan K Mutt

I have two lists:

我有两个清单:

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

I want to remove all occurrences of list2elements from list1, i.e. I want

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

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

I did list1 diff list2which gives me List("word2","word2","word3","word1")which is removing only the first occurrence of "word1".

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

I can not convert it to sets because I need knowledge about duplicates (see "word2" above). What to do?

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

回答by Rex Kerr

You can

你可以

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

to remove all items in list2. (You don't need knowledge of duplicates in list2.)

删除中的所有项目list2。(您不需要知道 . 中的重复项list2。)

回答by cmbaxter

You could try this:

你可以试试这个:

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

println(list1.filterNot(list2.contains(_)))

回答by Kuang Liang

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

This will do it.

这将做到。