-1

我有

{
  3=>[
    {63=>[5, 0, 1, 0]}, 
    {64=>[0, 0, 0, 0]},
    {65=>[0, 1, 2, 2]}
  ],
  1=>[
     {31=>[2, 0, 0, 0]},
     {32=>[0, 0, 3, 0]}
  ]
}

我需要转换成

{ 3 => [5,1,3,2], 1 => [2,0,3,0] }
4

3 回答 3

5
h= {
  3=>[
    {63=>[5, 0, 1, 0]},
    {64=>[0, 0, 0, 0]},
    {65=>[0, 1, 2, 2]}
  ],
  1=>[
     {31=>[2, 0, 0, 0]},
     {32=>[0, 0, 3, 0]}
  ]
}

p h.map{ |k, v| { k=> v.map(&:values).flatten(1).transpose.map{ |r| r.reduce(:+) } } }

# => [{3=>[5, 1, 3, 2]}, {1=>[2, 0, 3, 0]}]
于 2012-11-12T10:55:31.363 回答
4

这没什么难的,你只需要一点关注。

a = {
  3=>[
    {63=>[5, 0, 1, 0]}, 
    {64=>[0, 0, 0, 0]},
    {65=>[0, 1, 2, 2]}
  ],
  1=>[
     {31=>[2, 0, 0, 0]},
     {32=>[0, 0, 3, 0]}
  ]
}

b = a.each_with_object({}) do |(k, v), memo|
  res = []
  v.each do |h|
    h.each do |_, v2|
      v2.each_with_index do |el, idx|
        res[idx] ||= 0
        res[idx] += el
      end
    end
  end

  memo[k] = res
end

b # => {3=>[5, 1, 3, 2], 1=>[2, 0, 3, 0]}
于 2012-11-12T10:49:42.937 回答
2

这是一些可读的变量名称和基本解释。

a = {
  3=>[
    {63=>[5, 0, 1, 0]}, 
    {64=>[0, 0, 0, 0]},
    {65=>[0, 1, 2, 2]}
  ],
  1=>[
     {31=>[2, 0, 0, 0]},
     {32=>[0, 0, 3, 0]}
  ]
}

b = a.each_with_object({}) do |(key, sub_hashes), result|
  # Get the subarray for each nested hash (Ignore keys on the nested hashes)
  # Also flattening while mapping to get appropriate array of arrays
  value = sub_hashes.flat_map(&:values).
  # Transpose each row into a column 
  # e.g. [[5,0,1,0], [0,0,0,0], [0,1,2,2]] becomes [[5,0,0], [0,0,1], [1,0,2], [0,0,2]]
  transpose.
  # Sum each column
  # e.g. [1,0,2] = 1 + 0 + 2 = 3
  map { |column| column.reduce(0, :+) }

  # Update results set (Could also get rid of intermediate variable 'value' if you wish)
  result[key] = value
end

puts b # => {3=>[5, 1, 3, 2], 1=>[2, 0, 3, 0]}
puts b == {3 => [5,1,3,2], 1=>[2,0,3,0]}

编辑:现在使用 flat_map!

于 2012-11-12T17:47:58.267 回答