如何计算Ruby数组中的重复元素 [英] How to count duplicate elements in a Ruby array
本文介绍了如何计算Ruby数组中的重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个排序数组:
<预><代码>['FATAL <error title="请求超时.">','FATAL <error title="请求超时.">','FATAL我想得到这样的东西,但它不一定是散列:
<预><代码>[{:错误=>'FATAL <error title="请求超时.">', :count =>2},{:错误=>'FATAL <error title="系统内存不足,无法运行此查询.">', :count =>1}] 解决方案
以下代码打印您的要求.我会让你决定如何实际使用来生成你正在寻找的哈希:
# 示例数组a=["aa","bb","cc","bb","bb","cc"]# 使散列默认为 0,这样 += 才能正常工作b = Hash.new(0)# 遍历数组,计算重复条目a.每个都做|v|b[v] += 1结尾b. 各做 |k, v|puts "#{k} 出现 #{v} 次"结尾
注意:我刚刚注意到你说数组已经排序.上面的代码不需要排序.使用该属性可能会生成更快的代码.
I have a sorted array:
[
'FATAL <error title="Request timed out.">',
'FATAL <error title="Request timed out.">',
'FATAL <error title="There is insufficient system memory to run this query.">'
]
I would like to get something like this but it does not have to be a hash:
[
{:error => 'FATAL <error title="Request timed out.">', :count => 2},
{:error => 'FATAL <error title="There is insufficient system memory to run this query.">', :count => 1}
]
解决方案
The following code prints what you asked for. I'll let you decide on how to actually use to generate the hash you are looking for:
# sample array
a=["aa","bb","cc","bb","bb","cc"]
# make the hash default to 0 so that += will work correctly
b = Hash.new(0)
# iterate over the array, counting duplicate entries
a.each do |v|
b[v] += 1
end
b.each do |k, v|
puts "#{k} appears #{v} times"
end
Note: I just noticed you said the array is already sorted. The above code does not require sorting. Using that property may produce faster code.
这篇关于如何计算Ruby数组中的重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文