如何在列表中查找重复项? [英] How to find duplicates in a list?

查看:74
本文介绍了如何在列表中查找重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个未排序的整数列表,我想找到那些重复的元素.

I have a list of unsorted integers and I want to find those elements which have duplicates.

val dup = List(1,1,1,2,3,4,5,5,6,100,101,101,102)

我可以通过dup.distinct找到集合中的不同元素,所以我的回答如下.

I can find the distinct elements of the set with dup.distinct, so I wrote my answer as follows.

val dup = List(1,1,1,2,3,4,5,5,6,100,101,101,102)
val distinct = dup.distinct
val elementsWithCounts = distinct.map( (a:Int) => (a, dup.count( (b:Int) => a == b )) )
val duplicatesRemoved = elementsWithCounts.filter( (pair: Pair[Int,Int]) => { pair._2 <= 1 } )
val withDuplicates = elementsWithCounts.filter( (pair: Pair[Int,Int]) => { pair._2 > 1 } )

有没有更简单的方法来解决这个问题?

Is there an easier way to solve this?

推荐答案

尝试一下:

val dup = List(1,1,1,2,3,4,5,5,6,100,101,101,102)
dup.groupBy(identity).collect { case (x, List(_,_,_*)) => x }

groupBy将每个不同的整数与它的出现列表相关联. collect基本上是map,其中不匹配的元素将被忽略. case之后的匹配模式将匹配与List(_,_,_*)模式匹配的列表相关联的整数x,该列表具有至少两个元素,每个元素都由下划线表示,因为我们实际上不需要存储这些元素值(这两个元素后可以跟零个或多个元素:_*).

The groupBy associates each distinct integer with a list of its occurrences. The collect is basically map where non-matching elements are ignored. The match pattern following case will match integers x that are associated with a list that fits the pattern List(_,_,_*), a list with at least two elements, each represented by an underscore since we don't actually need to store those values (and those two elements can be followed by zero or more elements: _*).

您也可以这样做:

dup.groupBy(identity).collect { case (x,ys) if ys.lengthCompare(1) > 0 => x }

它比您提供的方法快得多,因为它不必重复传递数据.

It's much faster than the approach you provided since it doesn't have to repeatedly pass over the data.

这篇关于如何在列表中查找重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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