计算数组中的不同元素

编程入门 行业动态 更新时间:2024-10-21 10:21:09
本文介绍了计算数组中的不同元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数组:

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}

更多推荐

计算数组中的不同元素

本文发布于:2023-11-22 13:50:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!