Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
a = [[24, 18.0], [24, 16.0], [25, 15.0]]
我需要 b = [[24, 17.0], [25, 15.0]]
这是我需要计算子数组中第二项的平均值的两条规则,即[24, 18.0], [24, 16.0] #=> [24, 17.0]- 我可以自己单独完成,但我不明白如何将 reduce 与平均值结合起来,如“ruby way”解决方案a.collect{...}
[24, 18.0], [24, 16.0] #=> [24, 17.0]
a.collect{...}
您可以使用group_by对常用键进行分组,并sum/size获得平均值:
group_by
sum/size
b = a.group_by(&:first).map do |k,v| [k, v.map(&:last).inject(:+) / v.size] end