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 に答える