ruby中的数组x数组矩阵

时间:2013-09-29 14:19:59

标签: ruby arrays matrix

我想转换自

{'key1' => (1..10) ,
 'key2' => (11..20) , 
'key3' => (21..30)}

[{'key1' => 1, 'key2' => 11, 'key3' => 21},
{'key1' => 1, 'key2' => 11, 'key3' => 22},...
 .
 .
{'key1' => 10, 'key2' => 20, 'key3' => 30}]

如何解决?

6 个答案:

答案 0 :(得分:4)

这是:

hsh = {'key1' => (1..10) ,'key2' => (11..20) , 'key3' => (21..30)}
keys = hsh.keys
hsh['key1'].to_a.product(hsh['key2'].to_a,hsh['key3'].to_a).map{|a|Hash[keys.zip(a)]}

# => [{'key1' => 1, 'key2' => 11, 'key3' => 21},
#   {'key1' => 1, 'key2' => 11, 'key3' => 22},...
#   .
#   .
#   {'key1' => 10, 'key2' => 20, 'key3' => 30}]

当你有更多的键时,你也可以写下面的内容:

hsh = {'key1' => (1..10) ,'key2' => (11..20) , 'key3' => (21..30)}
keys = hsh.keys
array = hsh.values_at(*keys[1..-1]).map(&:to_a)
hsh['key1'].to_a.product(*array).map{|a|Hash[keys.zip(a)]}

答案 1 :(得分:2)

这么多方式......一个吻答案(编辑扩展到任意数量的键):

s = {'key1' => (1..10), 'key2' => (11..20), 'key3' => (21..30)}
r = []
s.each {|k,v| a = []; (v.to_a).each {|i| a << {k=>i}}; r << a}
result = r.shift
r.each {|e| result = result.product(e).map(&:flatten)}
result

答案 2 :(得分:2)

h = {
  'key1' => (1..10),
  'key2' => (11..20),
  'key3' => (21..30)
}

h.map { |k,v| [k].product(v.to_a) }.transpose.map { |e| Hash[e] }
#=> [{"key1"=>1, "key2"=>11, "key3"=>21},
#    {"key1"=>2, "key2"=>12, "key3"=>22},
#    {"key1"=>3, "key2"=>13, "key3"=>23},
#    {"key1"=>4, "key2"=>14, "key3"=>24},
#    {"key1"=>5, "key2"=>15, "key3"=>25},
#    {"key1"=>6, "key2"=>16, "key3"=>26},
#    {"key1"=>7, "key2"=>17, "key3"=>27},
#    {"key1"=>8, "key2"=>18, "key3"=>28},
#    {"key1"=>9, "key2"=>19, "key3"=>29},
#    {"key1"=>10, "key2"=>20, "key3"=>30}]

答案 3 :(得分:1)

h = {'key1' => (1..10) ,
'key2' => (11..20) , 
'key3' => (21..30)}

arrays = h.values.map(&:to_a).transpose
p arrays.map{|ar| Hash[h.keys.zip(ar)] }
#=> [{"key1"=>1, "key2"=>11, "key3"=>21}, {"key1"=>2, "key2"=>12, "key3"=>22},...

答案 4 :(得分:1)

h = {'key1' => (1..10), 'key2' => (11..20), 'key3' => (21..30)}

编辑1:进行了一些更改,主要是使用inject({})

f,*r = h.map {|k,v| [k].product(v.to_a)}
f.zip(*r).map {|e| e.inject({}) {|h,a| h[a.first] = a.last; h}}

编辑2:在@ Phrogz对another question的回答中看到使用Hash []之后:

f,*r = h.map {|k,v| [k].product(v.to_a)}
f.zip(*r).map {|e| Hash[*e.flatten]}

答案 5 :(得分:0)

拉齐尔做同样的方式:

h = {
  'key1' => (1..10),
  'key2' => (11..20),
  'key3' => (21..30)
}

result = ( 0...h.values.map( &:to_a ).map( &:size ).max ).map do |i|
  Hash.new { |hsh, k| hsh[k] = h[k].to_a[i] }
end

result[1]['key3'] #=> 22