【问题标题】:Create a nested hash创建嵌套哈希
【发布时间】:2015-10-02 15:00:29
【问题描述】:

我有一个这样的数组:

[
  {:game_id=>546012, :period=>:fg, :stat_name=>:hits, :result=>12, :team_id=>1104}, 
  {:game_id=>546012, :period=>:fg, :stat_name=>:errors, :result=>1, :team_id=>1104}, 
  {:game_id=>546012, :period=>:fg, :stat_name=>:hits, :result=>9, :team_id=>1103}, 
  {:game_id=>546012, :period=>:fg, :stat_name=>:errors, :result=>3, :team_id=>1103}
]

如何把它变成这样的数组:

{ 546012 => { :hits => { :fg => { 1104 => 12,  
                                  1103 => 9 } } 
              :errors => { :fg => { 1104 => 1,
                                  1103 => 3 } } }

【问题讨论】:

  • 您的预期结果不是(项目)数组。
  • 欢迎来到 Stack Overflow。 “寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题是没有用的给其他读者。见:How to create a Minimal, Complete, and Verifiable example。”

标签: arrays ruby hash nested


【解决方案1】:

首先,创建一个由 :game_id 组织的哈希

{ 546012 => {{
  {:period=>:fg, :stat_name=>:hits, :result=>12, :team_id=>1104},
  {:period=>:fg, :stat_name=>:errors, :result=>1, :team_id=>1104},
  {:period=>:fg, :stat_name=>:hits, :result=>9, :team_id=>1103},
  {:period=>:fg, :stat_name=>:errors, :result=>3, :team_id=>1103}
]}

然后按 :stat_name 分组

{ 546012 => [
  {:hits => [
     {:period=>:fg, :result=>12, :team_id=>1104},
     {:period=>:fg, :result=>9, :team_id=>1103}],
   :errors => [
     {:period=>:fg, :result=>1, :team_id=>1104},
     {:period=>:fg, :result=>3, :team_id=>1103}
   ]}
]}

然后按时期分组:

{ 546012 => [
  {:hits => [
     :fg => [{:result=>12, :team_id=>1104},
       {:result=>9, :team_id=>1103}]
     ]}
   ]},
   :errors => [
     :fg => [{:result=>1, :team_id=>1104},
       {:result=>3, :team_id=>1103}]
   ]}
]}

最后,按 :team_id 分组并将每一个与它的 :result 相关联。

{ 546012 => [
  {:hits => [
     :fg => [1104 => 12, 1103 => 9]
   ]},
   :errors => [
     :fg => [1104 => 1, 1103 => 3]
   ]}
]}

至于如何创建这些分组,我将作为练习留给你。

一种可能的方法是遍历每个项目并创建存储这些新映射的对象的新副本。例如,如果我们有这个对象:

foods = {
  {:food => lemon, :taste => sour},
  {:food => pretzel, :taste => salty},
  {:food => pretzel, :taste => sweet}
}

我们可以按食物分组,例如(伪代码):

newfoods = {};
foreach item in foods:
   newfoods[ item.food ].push( item.taste );

最终得到

newfoods = [
  { lemon => [sour] },
  { pretzel => [sweet, salty] }
]

【讨论】:

    【解决方案2】:

    您可以做的最佳选择是flatten it。

    学分转到this question

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2019-03-21
      • 2018-08-24
      • 1970-01-01
      相关资源
      最近更新 更多