本文介绍了计算数组中的不同元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组:
a = [1, 2, 3, 3, 6, 8, 1, 9]我要显示每个唯一元素值及其相关元素计数,如下所示:
I want to display each unique element value and its associated element count like this:
1: 2 2: 1 3: 2 6: 1 8: 1 9: 1到目前为止,我有:
a.sort.group_by { |x| x } { 1 => [ [0] 1, [1] 1 ], 2 => [ [0] 2 ], 3 => [ [0] 3, [1] 3 ], 6 => [ [0] 6 ], 8 => [ [0] 8 ], 9 => [ [0] 9 ] }因此,哈希的每个元素都包含一个数组.我可以使用该数组的计数来得到答案,但是在弄清楚如何简洁地处理哈希值时遇到了麻烦.
So each element of the Hash contains an array. I can use that array's count to get my answer, but I'm having trouble figuring out how to process the hash concisely.
这是一个可怕的实现吗?
Is this a horrible implementation?
a.sort.group_by { |x| x }.each {|x| puts "#{x[0]} #{x[1].count}" }推荐答案
怎么样:
a.inject({}) { |a,e| a[e] = (a[e] || 0) + 1; a } => {1=>2, 2=>1, 3=>2, 6=>1, 8=>1, 9=>1}例如:
h = a.inject({}) { |a,e| a[e] = (a[e] || 0) + 1; a } => {1=>2, 2=>1, 3=>2, 6=>1, 8=>1, 9=>1} h.keys.sort.each { |k| puts "#{k}: #{h[k]}" } 1: 2 2: 1 3: 2 6: 1 8: 1 9: 1摘自以下其他人的评论:
From comments of others below:
a.each_with_object(Hash.new(0)) { |e,a| a[e] += 1 } => {1=>2, 2=>1, 3=>2, 6=>1, 8=>1, 9=>1}更多推荐
计算数组中的不同元素
发布评论