在Ruby中,如何交换哈希上的密钥和值?在哈希中交换密钥和值
比方说,我有以下散列:
{:a=>:one, :b=>:two, :c=>:three}
,我想变成:
{:one=>:a, :two=>:b, :three=>:c}
使用地图显得相当繁琐。有一个更短的解决方案吗?
在Ruby中,如何交换哈希上的密钥和值?在哈希中交换密钥和值
比方说,我有以下散列:
{:a=>:one, :b=>:two, :c=>:three}
,我想变成:
{:one=>:a, :two=>:b, :three=>:c}
使用地图显得相当繁琐。有一个更短的解决方案吗?
Ruby有一个散列帮助方法,可以让你像对待散列那样对待散列。
{a: 1, b: 2, c: 3}.key(1)
=> :a
如果你想保持倒散,然后Hash#invert应适用于大多数情况。
{a: 1, b: 2, c: 3}.invert
=> {1=>:a, 2=>:b, 3=>:c}
但是...
如果有重复的值,invert
会丢弃所有,但最后你的价值观。同样key
只会返回第一场比赛。
{a: 1, b: 2, c: 2}.key(2)
=> :b
{a: 1, b: 2, c: 2}.invert
=> {1=>:a, 2=>:c}
所以..如果你的价值观是唯一可以使用Hash#invert
如果没有,那么你就可以把所有的值作为一个数组,像这样:
class Hash
# like invert but not lossy
# {"one"=>1,"two"=>2, "1"=>1, "2"=>2}.inverse => {1=>["one", "1"], 2=>["two", "2"]}
def safe_invert
each_with_object({}) do |(key,value),out|
out[value] ||= []
out[value] << key
end
end
end
注:此代码与测试是现在here。
或简称...
class Hash
def safe_invert
self.each_with_object({}){|(k,v),o|(o[v]||=[])<<k}
end
end
你打赌有一个!在Ruby中做事总有一个更简单的方法!
这很简单,只需使用Hash#invert
:
{a: :one, b: :two, c: :three}.invert
=> {:one=>:a, :two=>:b, :three=>:c}
的Et瞧!
如果相同的值在您的散列中多次出现,则散列#颠倒不起作用。 – Tilo
# this doesn't looks quite as elegant as the other solutions here,
# but if you call inverse twice, it will preserve the elements of the original hash
# true inversion of Ruby Hash/preserves all elements in original hash
# e.g. hash.inverse.inverse ~ h
class Hash
def inverse
i = Hash.new
self.each_pair{ |k,v|
if (v.class == Array)
v.each{ |x|
i[x] = i.has_key?(x) ? [k,i[x]].flatten : k
}
else
i[v] = i.has_key?(v) ? [k,i[v]].flatten : k
end
}
return i
end
end
Hash#inverse
为您提供:
h = {a: 1, b: 2, c: 2}
h.inverse
=> {1=>:a, 2=>[:c, :b]}
h.inverse.inverse
=> {:a=>1, :c=>2, :b=>2} # order might not be preserved
h.inverse.inverse == h
=> true # true-ish because order might change
而内置invert
方法刚刚打破:
h.invert
=> {1=>:a, 2=>:c} # FAIL
h.invert.invert == h
=> false # FAIL
这是迄今为止最好的答案。 – kwerle
使用阵列
input = {:key1=>"value1", :key2=>"value2", :key3=>"value3", :key4=>"value4", :key5=>"value5"}
output = Hash[input.to_a.map{|m| m.reverse}]
使用Hash
input = {:key1=>"value1", :key2=>"value2", :key3=>"value3", :key4=>"value4", :key5=>"value5"}
output = input.invert
files = {
'Input.txt' => 'Randy',
'Code.py' => 'Stan',
'Output.txt' => 'Randy'
}
h = Hash.new{|h,k| h[k] = []}
files.map {|k,v| h[v]<< k}
puts h
这将处理重复值了。
如果你有一个散列结果,其中的关键是是唯一的,你可以使用Hash#invert:
> {a: 1, b: 2, c: 3}.invert
=> {1=>:a, 2=>:b, 3=>:c}
这不会,如果你有非唯一键,工作然而,在只看到最后一个键会不停:
> {a: 1, b: 2, c: 3, d: 3, e: 2, f: 1}.invert
=> {1=>:f, 2=>:e, 3=>:d}
如果您有非唯一键的哈希,你可以这样做:
> hash={a: 1, b: 2, c: 3, d: 3, e: 2, f: 1}
> hash.each_with_object(Hash.new { |h,k| h[k]=[] }) {|(k,v), h|
h[v] << k
}
=> {1=>[:a, :f], 2=>[:b, :e], 3=>[:c, :d]}
如果散列值已经是数组,则可以这样做:
> hash={ "A" => [14, 15, 16], "B" => [17, 15], "C" => [35, 15] }
> hash.each_with_object(Hash.new { |h,k| h[k]=[] }) {|(k,v), h|
v.map {|t| h[t] << k}
}
=> {14=>["A"], 15=>["A", "B", "C"], 16=>["A"], 17=>["B"], 35=>["C"]}
非常相关!感谢您指出,我没有测试这些情况。 –
['each_with_object'](http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_with_object)在这里比'inject'更有意义。 –
这样就变成了'each_with_object({}){| i,o | k,v = * i; o [v] || = []; o [v] << k}'...好的 –