![](/img/trans.png)
[英]Iterate over array of hashes to sum values of one hash value based on another hash key
[英]sum array of hashes based on other fields in hash
我有一系列看起來像這樣的哈希:
[{:head_count=>150.5, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"},
{:head_count=>201.0, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"},
{:head_count=>103.5, :group=>"NW", :estimated_ship_date=>"201104", :yard=>"nyssa"}]
我正在尋找從看起來像這樣的數據哈希:
{
"wcc" =>
{
"NW" =>
{
"201105" => 351.5 # This being a sum
}
}
"nyssa" =>
{
"NW" =>
{
"201104" => 103.5 # This being a sum
}
}
}
我不確定我還能提供什么其他數據。
我嘗試了一次收集,但是甚至不知道從哪里開始。
謝謝
略有不同的版本,使用默認的哈希函數來自動更新容器:
a = [
{:head_count=>150.5, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"},
{:head_count=>201.0, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"},
{:head_count=>103.5, :group=>"NW", :estimated_ship_date=>"201104", :yard=>"nyssa"}
]
yards = Hash.new{ |h,yard|
h[yard]=Hash.new{ |h,group|
h[group]=Hash.new{ |h,est_date|
h[est_date]=0
}
}
}
a.each do |h|
yards[h[:yard]][h[:group]][h[:estimated_ship_date]] += h[:head_count]
end
p yards
#=> {"wcc"=>{"NW"=>{"201105"=>351.5}}, "nyssa"=>{"NW"=>{"201104"=>103.5}}}
我只是使用一個簡單的循環。
a = [{:head_count=>150.5, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"},
{:head_count=>201.0, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"},
{:head_count=>103.5, :group=>"NW", :estimated_ship_date=>"201104", :yard=>"nyssa"}]
yards = {}
a.each do |h|
yard = yards[h[:yard]] ||= {}
group = yard[h[:group]] ||= {}
group[h[:estimated_ship_date]] ||= 0.0
group[h[:estimated_ship_date]] += h[:head_count]
end
# yards => {"wcc"=>{"NW"=>{"201105"=>351.5}}, "nyssa"=>{"NW"=>{"201104"=>103.5}}}
x = [
{:head_count=>100, :group=>"NE", :estimated_ship_date=>"201103", :yard=>"wcc"},
{:head_count=>200, :group=>"NW", :estimated_ship_date=>"201104", :yard=>"wcc"},
{:head_count=>300, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"},
{:head_count=>400, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"},
{:head_count=>500, :group=>"NW", :estimated_ship_date=>"201104", :yard=>"nyssa"}]
p Hash[ x.group_by{ |i| i[:yard] }.map { |i,j|
[i, Hash[ j.group_by { |i| i[:group] }.map { |i,j|
[i, Hash[ j.group_by { |i| i[:estimated_ship_date] }.map{ |i,j|
[i, j.map{ |i| i[:head_count] }.inject(:+)]
} ] ]
} ] ]
} ]
{
"wcc"=>
{
"NE"=>
{
"201103"=>100
},
"NW"=>
{
"201104"=>200,
"201105"=>700
}
},
"nyssa"=>
{
"NW"=>
{
"201104"=>500
}
}
}
這是我的解決方案。
yards = []
a.select{|x| yards << x[:yard]}
sol = Hash.new{|k,v| k[v] = Hash.new{|k,v| k[v] = {} } }
yards.uniq.map do |x|
a.select{|y| x == y[:yard]}.flatten.map do |z|
sol[x][z[:group]][z[:estimated_ship_date]] = 0.0
sol[x][z[:group]][z[:estimated_ship_date]] += z[:head_count]
end
end
您的初始數組是a。 解決方案是溶膠。 我希望這看起來可讀
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.