Ruby在数组中平均集合的最佳方法是什么?

2 ruby

给定以下简单数据集,对于集合0 25 53和80的值的平均值的最佳方法是什么.

  [["0", "148.5"],
   ["0", "146.5"],
   ["0", "148.6"],
   ["0", "202.3"],
   ["25", "145.7"],
   ["25", "145.5"],
   ["25", "147.4"],
   ["25", "147.3"],
   ["53", "150.4"],
   ["53", "147.6"],
   ["53", "147.8"],
   ["53", "215.4"],
   ["80", "150.4"],
   ["80", "149.4"],
   ["80", "148.0"],
   ["80", "149.9"]]
Run Code Online (Sandbox Code Playgroud)

Jas*_*ins 6

注入足够简单.我经常在项目中实现一个通用的group_by方法来帮助这样的东西.

如果数据很大且性能问题,请考虑使用数字库或数据库(如果适用).

data = [ ... ]

groups = data.inject({}) do |hash, pair| 
  hash[pair.first] ||= []
  hash[pair.first] << pair.last.to_f
  hash
end

groups.inject({}) do |hash, pair| 
  hash[pair.first] = pair.last.inject(0,&:+) / pair.last.size
  hash
end
Run Code Online (Sandbox Code Playgroud)