1

我有几个哈希

hash1 = { :c1234 => 0.7, :c1237 => 0.8, :c1634 => 0.6, :c1224 => 0.3, :c1291 => 0.1 }
hash2 = { :c1234 => 0.5, :c1136 => 0.2, :c1634 => 0.7, :c1524 => 0.1, :c2291 => 0.9, :c2391 => 0.7 }
hash3 = { :c1234 => 0.3, :c1136 => 0.4, :c6321 => 0.5 }

我需要从这些哈希中创建矩阵,例如

numhash c1234 c1237 c1634 c1224 c1291 c1136 c1524 c2291 c2391 c6321
hash1     0.7   0.8   0.6   0.3   0.1     0     0     0     0     0
hash2     0.5     0   0.7     0     0   0.2   0.1   0.9   0.7     0
hash3     0.3     0     0     0     0   0.4     0     0     0   0.5

numhash = 3 (number of hashes)

请帮助我在 Ruby 中做到这一点。

4

3 回答 3

3

您不应将哈希值存储在许多局部变量中,而应将其存储在可枚举的集合中,例如数组或哈希。例如,使用散列来命名每个散列“行”:

data = {
  h1:     {c1234:0.7,c1237:0.8,c1634:0.6,c1224:0.3,c1291:0.1},
  cats:   {c1234:0.5,c1136:0.2,c1634:0.7,c1524:0.1,c2291:0.9,c2391:0.7},
  kittens:{c1234:0.3,c1136:0.4,c6321:0.5}
}

def print_grid(data)
  cols     = data.values.flat_map(&:keys).uniq.sort
  head     = data.keys.map(&:length).max
  template = "%#{head}s | #{cols.map{ |c| "%#{c.length}s" }.join(' | ')}"
  puts template % [ "", *cols ]
  data.each do |row,pairs|
    values = cols.map{ |col| pairs[col] || 0.0 }
    puts template % [ row, *values ]
  end
  puts "", "numhashes: #{data.length}"
end

print_grid(data)    
#=>         | c1136 | c1224 | c1234 | c1237 | c1291 | c1524 | c1634 | c2291 | c2391 | c6321
#=>      h1 |   0.0 |   0.3 |   0.7 |   0.8 |   0.1 |   0.0 |   0.6 |   0.0 |   0.0 |   0.0
#=>    cats |   0.2 |   0.0 |   0.5 |   0.0 |   0.0 |   0.1 |   0.7 |   0.9 |   0.7 |   0.0
#=> kittens |   0.4 |   0.0 |   0.3 |   0.0 |   0.0 |   0.0 |   0.0 |   0.0 |   0.0 |   0.5
#=> 
#=> numhashes: 3

如果您将最后一张地图更改为...

values = columns.map{ |col| pairs[col] || "-" }

然后你得到:

        | c1136 | c1224 | c1234 | c1237 | c1291 | c1524 | c1634 | c2291 | c2391 | c6321
     h1 |     - |   0.3 |   0.7 |   0.8 |   0.1 |     - |   0.6 |     - |     - |     -
   cats |   0.2 |     - |   0.5 |     - |     - |   0.1 |   0.7 |   0.9 |   0.7 |     -
kittens |   0.4 |     - |   0.3 |     - |     - |     - |     - |     - |     - |   0.5
于 2012-05-15T15:11:06.893 回答
2
hash1 = {:c1234 => 0.7, :c1237 => 0.8, :c1634 => 0.6, :c1224 => 0.3, :c1291 => 0.1} 
hash2 = {:c1234 => 0.5, :c1136 => 0.2, :c1634 => 0.7, :c1524 => 0.1, :c2291 => 0.9, :c2391 => 0.7}
hash3 = {:c1234 => 0.3, :c1136 => 0.4, :c6321 => 0.5}

all_hashes = [hash1, hash2, hash3]
all_keys = all_hashes.flat_map(&:keys).uniq

puts "#{all_hashes.length}\t#{all_keys.join("\t")}"
all_hashes.each_with_index do | hash, i |
  puts "hash#{i}\t#{all_keys.map { | k | hash[k]}.join("\t")}"
end
于 2012-05-15T15:27:58.210 回答
0

尝试

numhash = { :hash1 => { :c1234=>0.7,:c1237=>0.8,:c1634=>0.6,:c1224=>0.3,:c1291=>0.1 }, :hash2 => { :c1234 => 0.5, :c1136 => 0.2, :c1634 => 0.7, :c1524 => 0.1, :c2291 => 0.9, :c2391 => 0.7} }

等等...然后您可以通过numhash[:hash1][:c1237]例如访问值。

于 2012-05-15T15:26:24.217 回答