[英]How to find the unique elements in an array in Ruby
I have an array with some elements.我有一个包含一些元素的数组。 How can I get the number of occurrences of each element in the array?
如何获取数组中每个元素的出现次数?
For example, given:例如,给定:
a = ['cat', 'dog', 'fish', 'fish']
The result should be:结果应该是:
a2 #=> {'cat' => 1, 'dog' => 1, 'fish' => 2}
How can I do that?我怎样才能做到这一点?
You can use Enumerable#group_by
to do this:您可以使用
Enumerable#group_by
来执行此操作:
res = Hash[a.group_by {|x| x}.map {|k,v| [k,v.count]}]
#=> {"cat"=>1, "dog"=>1, "fish"=>2}
a2 = a.reduce(Hash.new(0)) { |a, b| a[b] += 1; a }
#=> {"cat"=>1, "fish"=>2, "dog"=>1}
a2 = {}
a.uniq.each{|e| a2[e]= a.count(e)}
In 1.9.2 you can do it like this, from my experience quite a lot of people find each_with_object
more readable than reduce/inject
(the ones who know about it at least):在 1.9.2 中你可以这样做,根据我的经验,很多人发现
each_with_object
比reduce/inject
更具可读性(至少知道它的人):
a = ['cat','dog','fish','fish']
#=> ["cat", "dog", "fish", "fish"]
a2 = a.each_with_object(Hash.new(0)) { |animal, hash| hash[animal] += 1 }
#=> {"cat"=>1, "dog"=>1, "fish"=>2}
Ruby 2.7 has tally method for this. Ruby 2.7 对此有 计数方法。
tally → a_hash计数 → a_hash
Tallies the collection, ie, counts the occurrences of each element.统计集合,即计算每个元素的出现次数。 Returns a hash with the elements of the collection as keys and the corresponding counts as values.
返回一个 hash ,其中集合的元素作为键,相应的计数作为值。
['cat', 'dog', 'fish', 'fish'].tally
=> {"cat"=>1, "dog"=>1, "fish"=>2}
m = {}
a.each do |e|
m[e] = 0 if m[e].nil?
m[e] = m[e] + 1
end
puts m
['cat','dog','fish','fish'].group_by(&:itself).transform_values(&:count) => { "cat" => 1, "dog" => 1, "fish" => 2 }
a.inject({}){|h, e| h[e] = h[e].to_i+1; h }
#=> {"cat"=>1, "fish"=>2, "dog"=>1}
or n2 solution或 n2 溶液
a.uniq.inject({}){|h, e| h[e] = a.count(e); h }
#=> {"cat"=>1, "fish"=>2, "dog"=>1}
a = ['cat','dog','fish','fish']
a2 = Hash[a.uniq.map {|i| [i, a.count(i)]}]
a = ['cat','dog','fish','fish']
a2 = Hash.new(0)
a.each do |e|
a2[e] += 1
end
a2
ruby fu! ruby 福!
count = Hash[Hash[rows.group_by{|x| x}.map {|k,v| [k, v.count]}].sort_by{|k,v| v}.reverse]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.