0

我有这样的事情:

a = [{"group_id" => 1, "student_id" => 3, "candies" => 4},
  {"group_id" => 2, "student_id" => 1, "candies" => 3},
  {"group_id" => 1, "student_id" => 2, "candies" => 2},
  {"group_id" => 3, "student_id" => 4, "candies" => 6},
  {"group_id" => 1, "student_id" => 5, "candies" => 1},
  {"group_id" => 3, "student_id" => 6, "candies" => 1},
  {"group_id" => 4, "student_id" => 8, "candies" => 3}]

我有三组学生,每个学生得到一定数量的糖果。我想计算一组糖果的总数。为此,我需要知道属于某个组的学生并累积他们的糖果数。我可以使用循环并将计数初始化为零来做到这一点:

aa = a.group_by { |a| a["group_id"] }
# =>
{
  1 => [
    {"group_id"=>1, "student_id"=>3, "candies"=>4},
    {"group_id"=>1, "student_id"=>2, "candies"=>2},
    {"group_id"=>1, "student_id"=>5, "candies"=>1}
  ],
  2 => [{"group_id"=>2, "student_id"=>1, "candies"=>3}],
  3 => [
    {"group_id"=>3, "student_id"=>4, "candies"=>6},
    {"group_id"=>3, "student_id"=>6, "candies"=>1}
  ],
  4 => [{"group_id"=>4, "student_id"=>8, "candies"=>3}]
}

但我无法在group_id. 我想知道是否有任何简洁的方式来表示它。我如何总结一组中的糖果总数?

4

3 回答 3

1

您的第一步(分组)是正确的。之后,您可以使用以下内容:

a.group_by {|g| g['group_id']}.map do |g, students|
  {group_id:g, candies:students.map {|st| st['candies']}.inject(&:+)}
end

map函数通常与集合一起使用而不是循环来对每个元素进行一些操作并返回集合的修改版本。

输出:

[{:group_id=>1, :candies=>7}, 
 {:group_id=>2, :candies=>3}, 
 {:group_id=>3, :candies=>7}, 
 {:group_id=>4, :candies=>3}]
于 2013-07-12T16:56:25.777 回答
0

添加到@StasS 答案,一种更直接的哈希方法(使用更神秘的代码)是这样的:

> Hash[a.group_by{|g| g['group_id']}.map{|g,s| [g, s.inject(0){|a,b| a + b["candies"]}]}]
 => {1=>7, 2=>3, 3=>7, 4=>3} 

你可以像这样展开这条线:

groups = a.group_by{|g| g['group_id']}
id_candies_pairs = groups.map{|g,s| [g, s.inject(0){|a,b| a + b["candies"]}]}
id_candies_hash = Hash[id_candies_pairs]
return id_candies_hash
于 2013-07-12T18:08:09.923 回答
0

根据@StasS 的答案,您还可以构建一个看起来更简单的哈希,例如:

totals_by_group_id = {}  
a.group_by {|g| g['group_id']}.map do |g, students|  
  totals_by_group_id[g] = students.map {|st| st['candies']}.inject(&:+)  
end

生成的 totals_by_group_id 哈希为:

{1=>7, 2=>3, 3=>7, 4=>3}
于 2013-07-12T18:08:13.770 回答