如何选择独特的元素 [英] How to select unique elements

查看:21
本文介绍了如何选择独特的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个 uniq_elements 方法扩展 Array 类,该方法返回重数为 1 的那些元素.我还想对我的新方法使用闭包,就像 uniq 一样.例如:

I would like to extend the Array class with a uniq_elements method which returns those elements with multiplicity of one. I also would like to use closures to my new method as with uniq. For example:

t=[1,2,2,3,4,4,5,6,7,7,8,9,9,9]
t.uniq_elements # => [1,3,5,6,8]

闭包示例:

t=[1.0, 1.1, 2.0, 3.0, 3.4, 4.0, 4.2, 5.1, 5.7, 6.1, 6.2]
t.uniq_elements{|z| z.round} # => [2.0, 5.1]

t-t.uniqt.to_set-t.uniq.to_set 都不起作用.我不在乎速度,我在我的程序中只调用了一次,所以可能会很慢.

Neither t-t.uniq nor t.to_set-t.uniq.to_set works. I don't care of speed, I call it only once in my program, so it can be a slow.

推荐答案

Helper 方法

这个方法使用了helper:

This method uses the helper:

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

这个方法类似于Array#-.以下示例说明了差异:

This method is similar to Array#-. The difference is illustrated in the following example:

a = [3,1,2,3,4,3,2,2,4]
b = [2,3,4,4,3,4]

a - b              #=> [1]
c = a.difference b #=> [1, 3, 2, 2] 

如您所见,a 包含三个 3,b 包含两个,所以 a 中的 first 两个 3> 在构造 c 时被删除(a 没有发生变异).当 b 包含与 a 一样多的元素实例时,c 不包含该元素的实例.删除以 a 结尾的元素:

As you see, a contains three 3's and b contains two, so the first two 3's in a are removed in constructing c (a is not mutated). When b contains as least as many instances of an element as does a, c contains no instances of that element. To remove elements beginning at the end of a:

a.reverse.difference(b).reverse #=> [3, 1, 2, 2]

Array#difference! 可以用显而易见的方式定义.

Array#difference! could be defined in the obvious way.

我发现这种方法有很多用途:在这里此处此处这里这里这里这里此处此处此处此处此处此处此处此处此处此处此处此处此处此处此处此处.

I have found many uses for this method: here, here, here, here, here, here, here, here, here, here, here, here, here, here, here, here, here, here, here, here, here, here and here.

建议将此方法添加到 Ruby 核心.

I have proposed that this method be added to the Ruby core.

当与Array#-一起使用时,这个方法可以很容易地从数组a中提取唯一元素:

When used with Array#-, this method makes it easy to extract the unique elements from an array a:

a = [1,3,2,4,3,4]
u = a.uniq          #=> [1, 2, 3, 4]
u - a.difference(u) #=> [1, 2]

这是可行的,因为

a.difference(u)     #=> [3,4]    

包含 a 的所有非唯一元素(每个元素可能不止一次).

contains all the non-unique elements of a (each possibly more than once).

手头的问题

代码

class Array
  def uniq_elements(&prc)
    prc ||= ->(e) { e }
    a = map { |e| prc[e] }
    u = a.uniq
    uniques = u - a.difference(u)
    select { |e| uniques.include?(prc[e]) ? (uniques.delete(e); true) : false }
  end
end

示例

t = [1,2,2,3,4,4,5,6,7,7,8,9,9,9]
t.uniq_elements
  #=> [1,3,5,6,8]

t = [1.0, 1.1, 2.0, 3.0, 3.4, 4.0, 4.2, 5.1, 5.7, 6.1, 6.2]
t.uniq_elements { |z| z.round }
  # => [2.0, 5.1]

这篇关于如何选择独特的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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