如何检查数组的重复?(复制)

时间:2021-11-27 07:40:41

This question already has an answer here:

这个问题已经有了答案:

I've got an array A. I'd like to check if it contains duplicate values. How would I do so?

我有一个数组a,我想检查它是否包含重复的值。我该怎么做呢?

4 个解决方案

#1


115  

Just call uniq on it (which returns a new array without duplicates) and see whether the uniqed array has less elements than the original:

只需调用uniq(它返回一个没有重复的新数组)并查看uniqed数组的元素是否比原始数组少:

if a.uniq.length == a.length
  puts "a does not contain duplicates"
else
  puts "a does contain duplicates"
end

Note that the objects in the array need to respond to hash and eql? in a meaningful for uniq to work properly.

注意数组中的对象需要响应散列和eql?这对uniq来说是有意义的工作。

#2


33  

In order to find the duplicated elements, I use this approach (with Ruby 1.9.3):

为了找到重复的元素,我使用了这种方法(使用Ruby 1.9.3):

array = [1, 2, 1, 3, 5, 4, 5, 5]
=> [1, 2, 1, 3, 5, 4, 5, 5]
dup = array.select{|element| array.count(element) > 1 }
=> [1, 1, 5, 5, 5]
dup.uniq
=> [1, 5]

#3


9  

If you want to return the duplicates, you can do this:

如果你想要返回副本,你可以这样做:

dups = [1,1,1,2,2,3].group_by{|e| e}.keep_if{|_, e| e.length > 1}
# => {1=>[1, 1, 1], 2=>[2, 2]}

If you want just the values:

如果你只想要值:

dups.keys
# => [1, 2]

If you want the number of duplicates:

如果你想要复制的数量:

dups.map{|k, v| {k => v.length}}
# => [{1=>3}, {2=>2}]

#4


4  

Might want to monkeypatch Array if using this more than once:

如果多次使用monkeypatch数组:

class Array
  def uniq?
    self.length == self.uniq.length
  end
end

Then:

然后:

irb(main):018:0> [1,2].uniq?
=> true
irb(main):019:0> [2,2].uniq?
=> false

#1


115  

Just call uniq on it (which returns a new array without duplicates) and see whether the uniqed array has less elements than the original:

只需调用uniq(它返回一个没有重复的新数组)并查看uniqed数组的元素是否比原始数组少:

if a.uniq.length == a.length
  puts "a does not contain duplicates"
else
  puts "a does contain duplicates"
end

Note that the objects in the array need to respond to hash and eql? in a meaningful for uniq to work properly.

注意数组中的对象需要响应散列和eql?这对uniq来说是有意义的工作。

#2


33  

In order to find the duplicated elements, I use this approach (with Ruby 1.9.3):

为了找到重复的元素,我使用了这种方法(使用Ruby 1.9.3):

array = [1, 2, 1, 3, 5, 4, 5, 5]
=> [1, 2, 1, 3, 5, 4, 5, 5]
dup = array.select{|element| array.count(element) > 1 }
=> [1, 1, 5, 5, 5]
dup.uniq
=> [1, 5]

#3


9  

If you want to return the duplicates, you can do this:

如果你想要返回副本,你可以这样做:

dups = [1,1,1,2,2,3].group_by{|e| e}.keep_if{|_, e| e.length > 1}
# => {1=>[1, 1, 1], 2=>[2, 2]}

If you want just the values:

如果你只想要值:

dups.keys
# => [1, 2]

If you want the number of duplicates:

如果你想要复制的数量:

dups.map{|k, v| {k => v.length}}
# => [{1=>3}, {2=>2}]

#4


4  

Might want to monkeypatch Array if using this more than once:

如果多次使用monkeypatch数组:

class Array
  def uniq?
    self.length == self.uniq.length
  end
end

Then:

然后:

irb(main):018:0> [1,2].uniq?
=> true
irb(main):019:0> [2,2].uniq?
=> false