如何获得两个列表之间的差异? [英] How to get the difference between two lists?

查看:43
本文介绍了如何获得两个列表之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

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

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

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

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

我做了 list1 diff list2 这给了我 List("word2","word2","word3","word1"),该列表仅删除了第一次出现的"word1".

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

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

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

推荐答案

您可以使用

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

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

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

这篇关于如何获得两个列表之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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