programing

해시에서 키와 값을 교환하는 방법

telecom 2023. 6. 19. 21:08
반응형

해시에서 키와 값을 교환하는 방법

해시에서 키와 값을 교환하려면 어떻게 해야 합니까?

해시가 다음과 같습니다.

{:a=>:one, :b=>:two, :c=>:three}

내가 변화시키고 싶은 것:

{:one=>:a, :two=>:b, :three=>:c}

사용.map다소 지루해 보입니다.더 짧은 해결책이 있습니까?

Ruby는 Hash에 대한 도우미 방법을 사용하여 Hash를 반전된 것처럼 처리할 수 있습니다(기본적으로 값을 통해 키에 액세스할 수 있음).

{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

참고: 테스트가 포함된 이 코드는 이제 GitHub에 있습니다.

또는:

class Hash
  def safe_invert
    self.each_with_object({}){|(k,v),o|(o[v]||=[])<<k}
  end
end

틀림없이 하나가 있을 거예요!루비에는 항상 더 짧은 방법이 있습니다!

매우 간단하므로 다음을 사용합니다.

{a: :one, b: :two, c: :three}.invert
=> {:one=>:a, :two=>:b, :three=>:c}

에트볼랴!

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

이렇게 하면 중복 값도 처리됩니다.

키가 고유한 해시가 있는 경우 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"]}
# 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

배열 사용

input = {:key1=>"value1", :key2=>"value2", :key3=>"value3", :key4=>"value4", :key5=>"value5"}
output = Hash[input.to_a.map{|m| m.reverse}]

해시 사용

input = {:key1=>"value1", :key2=>"value2", :key3=>"value3", :key4=>"value4", :key5=>"value5"}
output = input.invert

언급URL : https://stackoverflow.com/questions/10989259/how-to-swap-keys-and-values-in-a-hash

반응형