具有重复键的哈希数组中的平均值

问题描述 投票:3回答:5

我有一系列哈希设置如下:

array = [
  {"1" => 1, "2" => 2, "3" =>3},
  {"1" => 1, "2" => 2, "3" =>3}, 
  {"1" => 1, "2" => 2, "3" =>3}
]

我试图找到一种方法来平衡所有哈希的值与关键"1",例如。

有人可以帮忙吗?

arrays ruby hash average
5个回答
2
投票

考虑到Ruby版本,yield_self(别名)可能会起作用:

[{ "1" => 10, "2" => 2, "3" =>3 },
 { "1" => 43, "2" => 2, "3" =>3 },
 { "1" => 4, "2" => 2, "3" =>3 }].map { |hash| hash.fetch('1', 0) }.then { |arr| arr.sum.fdiv(arr.size) }
# 19.0

(10 + 43 + 4) / 3 = 19.0,不是你的例子,而不仅仅是1 + 1 + 1。


4
投票

Array现在有一个sum方法,需要一个块。它基本上总结了块返回的内容:

array = [{"1" => 0, "2" => 2, "3" =>3}, {"1" => 1, "2" => 4, "3" =>6}, {"1" => 2, "2" => 6, "3" =>9}]
array.sum{|h| h['1']}.fdiv(array.size)

0
投票

我会做这样的事情:

array = [{"1" => 1, "2" => 2, "3" =>3},{"1" => 1, "2" => 2, "3" =>3},{"1" => 1, "2" => 2, "3" =>3}]
array.map { |hash| hash['1'] }.inject { |sum, el| sum + el }.to_f / array.size
#=> 1.0

在本例中,array.map { |hash| hash['1'] }使用密钥'1'[1,1,1])提取所有元素的值。而.inject{ |sum, el| sum + el }.to_f / array.size计算平均值。


0
投票

给定数组(我更改了值以便于调试):

array = [{"1" => 0, "2" => 2, "3" =>3}, {"1" => 1, "2" => 4, "3" =>6}, {"1" => 2, "2" => 6, "3" =>9}]

此代码将每个键映射到值的平均值:

array.each_with_object(Hash.new{ |k,v| k[v] = [ ]}) { |h, hh| h.each { |k,v| hh[k] << v } }.transform_values { |k| k.sum.to_f/k.size }

#=>  {"1"=>1.0, "2"=>4.0, "3"=>6.0}


Methods used:

0
投票
array_data = [
  {"1" => 1, "2" => 2, "3" =>3}, 
  {"1" => 1, "2" => 2, "3" =>3}, 
  {"1" => 1, "2" => 2, "3" =>3}
]

class Hash
  def get_first
    self['1']
  end
end

class Array
  def avg
    sum / size
  end
end

avg = array_data.map(&:get_first).avg
© www.soinside.com 2019 - 2024. All rights reserved.