Ruby:从数组中删除所有重复值的实例

4
我有一个数组,希望能够移除其中所有重复的值。以下是需要翻译的内容:

arr = [1, 1, 2, 3, 4, 4, 5]

期望的输出结果为:

=> [2, 3, 5]

您认为最好的方法是什么?


为什么急于选择答案? - Cary Swoveland
6个回答

7
p arr.group_by(&:itself).reject{|k,v|v.count>1}.keys

输出

[2, 3, 5]

3

这里有三种方法可以实现(@Rajagopalan的答案是其中之一)。

arr = [1, 1, 2, 3, 4, 4, 5]

使用计数哈希表。
arr.each_with_object(Hash.new(0)) { |n,h| h[n] += 1 }.select { |_,v| v == 1 }.keys
  # => [2, 3, 5]

使用 Array#count
arr.uniq.select { |n| arr.count(n) == 1 }
  #=> [2, 3, 5]

这可能看起来相对低效,因为每个 arr.uniq 元素都需要遍历 arr。但是,如果 arr.uniq 不太大,实际上比使用计数哈希表或(如 Rajagopalan 所做的)Enumerable#group_by 更快。
使用 Array#difference 方法。 Array#difference 是我建议添加到 Ruby 核心的方法。
class Array
  def difference(other)
    h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
    reject { |e| h[e] > 0 && h[e] -= 1 }
  end
end

如果我们可以使用那种方法,我们就可以写出以下内容。
arr - arr.difference(arr.uniq)
  #=> [2, 3, 5] 

arr.each_with_object({}) { |e, h| h[e] = !h[e] & 0}.select{|_,v| v }.keys - Ingo
@Ingo,如果 arr = [1,1,1],则返回 [1](因为对于给定的 eh[e] = !h[e] & 00false 之间交替)。 - Cary Swoveland

1
arr = [1, 1, 2, 3, 4, 4, 5]
arr.reject{|x| arr.count(x)>1}

预期输出
=> [2, 3, 5]

如果它是多维的
multi_array = [[33], [34], [35], [34, 35], [34, 35], [36], [30, 31], [30, 31], [30, 31, 32], [32, 33]] 
multi_flatten = multi_array.flatten
#=> [33, 34, 35, 34, 35, 34, 35, 36, 30, 31, 30, 31, 30, 31, 32, 32, 33]
multi_flatten.reject{|x| multi_flatten.count(x)>1}
#=> [36]

请在您的答案中添加上下文。 - Vendetta

1

有一个更简单的解决方案:

arr = [1, 2, 1, 3, 1, 4, 1, 5, 1, 6]

new_arr = arr - [1]

new_arr 返回 [2, 3, 4, 5, 6]


0

enter image description here

+1 for: arr.uniq.select { |n| arr.count(n) == 1 } seems to be more readable and clean

@cary-swoveland Array#difference 看起来有一些性能问题。


-2

这确实提供了唯一的值,但我想要删除所有唯一的值。 - endex
1
我的错 - 上面 @Rajagopalan 的答案似乎更准确。 - Mark
是的,他想要移除重复元素。 - Rajagopalan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接