3

使用 Ruby 我需要将其转换为...

{"30"=>["Morgan", ["lib1", "lib2"]], 
 "31"=>["Morgan", ["lib9", "lib2", "lib3"]], 
 "32"=>["Gary", ["lib1", "lib2"]], 
 "33"=>["Morgan", ["lib1"]], 
 "34"=>["Morgan", []], 
 "35"=>["Morgan", []], 
 "36"=>["Morgan", ["lib3", "lib2"]], 
 "37"=>["jim", ["lib1"]]}

进入这个...

{"Morgan"=>[30,31,33,34,35,36], 
 "Gary"=>[32], []=>[34,35], 
 "jim"=>[37]}

有任何想法吗?

4

4 回答 4

2
input.each_with_object(Hash.new{|h,k|h[k]=[]}) do |(k,v),res|
  (v.last.empty? ? res[[]] : res[v.first]) << k.to_i
end

=> {"Morgan"=>[30, 31, 33, 36], "Gary"=>[32], []=>[34, 35], "jim"=>[37]}
于 2012-10-22T00:19:40.410 回答
0
A = {"30"=>["Morgan", ["lib1", "lib2"]], 
 "31"=>["Morgan", ["lib9", "lib2", "lib3"]], 
 "32"=>["Gary", ["lib1", "lib2"]], 
 "33"=>["Morgan", ["lib1"]], 
 "34"=>["Morgan", []], 
 "35"=>["Morgan", []], 
 "36"=>["Morgan", ["lib3", "lib2"]], 
 "37"=>["jim", ["lib1"]]}

B = Hash.new;
A.each do |k,i|
    if !B[i[0]].kind_of?(Array)
        B[i[0]] = Array.new;
    end
    B[i[0]]<<k
    puts "#{k} #{i[0]}"

end

B.each do |k,i|
    puts "#{k} #{i}"
end

作为示例代码:)

于 2012-10-22T00:14:43.563 回答
0
newhash={}    
hash.inver­t.each {|k,v­| newha­sh[k.first­].concat [v] }

invert方法对您想要做的事情很有用。但我看不出值的“lib”部分与转换有何关系。请说清楚。

于 2012-10-22T00:08:41.473 回答
0
def convert(input)          
    output = {}                     
    noLibKey = []                   
    input.each do |key, value|      
            number = key.to_i               
            name = value[0]                 
            libs = value[1]                 
            if libs.empty?                  
                    output[noLibKey] ||= []         
                    output[noLibKey] << number      
            end                             
            output[name] ||= []             
            output[name] << number          
    end                             
    return output                   
end
于 2012-10-22T00:08:45.520 回答