Ruby Merge列表哈希&获得平均值

时间:2014-01-17 05:43:34

标签: ruby

我有以下哈希列表:

[{"day":3,"count":2},{"day":1,"count":2},{"day":1,"count":2},{"day":2,"count":2},{"day":1,"count":2},{"day":4,"count":2},{"day":5,"count":2},{"day":6,"count":2},{"day":4,"count":2},{"day":4,"count":2},{"day":3,"count":2},{"day":3,"count":2},{"day":2,"count":2},{"day":6,"count":2},{"day":0,"count":2},{"day":5,"count":2},{"day":0,"count":2},{"day":5,"count":2},{"day":4,"count":2},{"day":1,"count":2},{"day":0,"count":2},{"day":0,"count":2},{"day":2,"count":2},{"day":2,"count":2},{"day":2,"count":2},{"day":1,"count":2},{"day":6,"count":2},{"day":5,"count":2},{"day":3,"count":2},{"day":2,"count":2},{"day":2,"count":2},{"day":1,"count":2},{"day":5,"count":2},{"day":4,"count":2},{"day":2,"count":2}]

我希望将具有相同“日期”值的所有密钥合并在一起,然后获得第二个键/值对的平均值的平均值。

例如,我的最终输出应如下所示:

[{"day":0, "count": 2}, {"day":1, "count": 2}, {"day":3, "count": 2}, {"day":4, "count": 2}, {"day":5, "count": 2}, {"day":6, "count": 2}, {"day":7, "count": 2},]

计算平均值实际上是计算的(并非总是“2”),我只是以两个为例。

2 个答案:

答案 0 :(得分:3)

# group the list into sublists sharing the same day
data.group_by { |element| element['day'] }.map { |day, element_list|
  # for each day, return a new object
  {
    day:   day,
    # extract the count from all the elements in the sublist,
    # then add them together and divide by number of elements
    # (convert to float to avoid integral division)
    count: element_list.map { |element| element['count'] }.
             reduce(:+).to_f / element_list.size
  }
}

答案 1 :(得分:2)

如果您的哈希集合被称为data

,这将有效
days = data.group_by{|record| record["day"] }
days.map do |day, records|
  {day: day, count: records.map{|record| record["count"] }.average}
end