如何在Hash中交换键和值?
我有以下哈希:
{:a=>:one, :b=>:two, :c=>:three}
我想要转换成:
{:one=>:a, :two=>:b, :three=>:c}
使用map
似乎相当乏味。有没有更短的解决方案?
发布于 2012-06-12 08:46:16
我敢打赌肯定有一个!在Ruby中总是有一种更短的方法来做事情!
这很简单,只需使用Hash#invert
{a: :one, b: :two, c: :three}.invert
=> {:one=>:a, :two=>:b, :three=>:c}
就是这样!
发布于 2017-03-21 11:39:34
files = {
'Input.txt' => 'Randy',
'Code.py' => 'Stan',
'Output.txt' => 'Randy'
}
h = Hash.new{|h,k| h[k] = []} # Create hash that defaults unknown keys to empty an empty list
files.map {|k,v| h[v]<< k} #append each key to the list at a known value
puts h
这也将处理重复的值。
发布于 2017-07-20 06:23:16
如果您有一个散列,其中的键是唯一的,则可以使用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"]}
https://stackoverflow.com/questions/10989259
复制相似问题