如何在散列数组中计算某些键值的频率?

时间:2011-03-06 04:29:53

标签: ruby

我有一系列哈希。每个哈希都有一个uses密钥。多个哈希值可以共享相同的uses值。

[{uses => 0},{uses => 1},{uses => 2},{uses => 1},{uses => 0},{uses => 1},{uses => 3}]

如何按降序生成最常见uses值的数组?

[1,0,2,3]

3 个答案:

答案 0 :(得分:2)

引用this discussion of frequency of items in a list,我们可以轻松地为您的任务修改此内容。

> unsorted = [{:uses=>0}, {:uses=>1}, {:uses=>2}, {:uses=>1}, {:uses=>0}, {:uses=>1}, {:uses=>3}].map{|h| h[:uses]}
> sorted = unsorted.uniq.sort_by{|u| unsorted.grep(u).size}.reverse
 => [1, 0, 2, 3] 

答案 1 :(得分:1)

hs.inject({}) do |histogram, h|
  histogram.merge(h[:uses] => (histogram[h[:uses]] || 0) + 1)
end.sort_by { |k, v| -v }.map { |k, v| k }
# => [1, 0, 2, 3]

我总是建议使用Facets:

http://rubyworks.github.com/facets/doc/api/core/Enumerable.html

hs.frequency.sort_by { |k, v| -v }.map { |k, v| k }
# => [1, 0, 2, 3]

答案 2 :(得分:0)

以下是单程解决方案:

a = [{:uses => 0},{:uses => 1},{:uses => 2},{:uses => 1},{:uses => 0},
  {:uses => 1},{:uses => 3}]

# A hash with the frequency count is formed in one iteration of the array
# followed by the reverse sort and extraction

a.inject(Hash.new(0)) { |h, v| h[v[:uses]] += 1;h}.
  sort{|x, y| x <=> y}.map{|kv| kv[0]}