在哈希中查找重复的密钥? [英] Finding duplicate keys across hashes?

查看:110
本文介绍了在哈希中查找重复的密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为简化起见,我们假设下面有哈希值.

To simplify things let's say I have the hashes below.

我想找到多个散列中的键和散列的名称.所以理想情况下,我想结束

I would like to find the keys that are in multiple hashes and the name of the hashes. So ideally I would like to end up with

A is also in  a
A is also in  b
B is also in  a
B is also in  b
D is also in  b
D is also in  c
E is also in  b
E is also in  c

我能想到的唯一方法是:将所有键放入一个数组中,对其进行排序,删除唯一的元素,搜索包含剩下的数组元素的每个哈希.

The only way I can think of is: putting all keys in an array, sort it, remove unique elements, search each hash that contain the remaing array elements.

我想这有点复杂和棘手.

It is somewhat complicated and hacky I guess.

问题

是否有更简单的方法来查找散列中的重复密钥?

Is there an easier way to find duplicate keys across hashes?

!/usr/bin/ruby                                                                                          

require 'ap'

a = {}
b = {}
c = {}

a["A"] = 1
a["B"] = 1
a["C"] = 1

b["A"] = 1
b["B"] = 1
b["D"] = 1
b["E"] = 1

c["D"] = 1
c["E"] = 1
c["F"] = 1

推荐答案

您可以构建另一个散列来存储每个键及其散列:

You could build another hash to store each key and its hashes:

keys = Hash.new { |hash, key| hash[key] = [] }
a.each_key { |k| keys[k] << :a }
b.each_key { |k| keys[k] << :b }
c.each_key { |k| keys[k] << :c }

更准确地说,keys存储符号数组.运行上面的代码后,看起来像这样:

More precisely, keys stores an array of symbols. It looks like this after running the above code:

keys
#=> {"A"=>[:a, :b],
#    "B"=>[:a, :b],
#    "C"=>[:a],
#    "D"=>[:b, :c],
#    "E"=>[:b, :c],
#    "F"=>[:c]}

要获得预期的输出,请执行以下操作:

To get your expected output:

keys.each do |key, hashes|
  next if hashes.size < 2
  hashes.each { |hash| puts "#{key} is also in #{hash}" }
end

打印:

A is also in a
A is also in b
B is also in a
B is also in b
D is also in b
D is also in c
E is also in b
E is also in c

这篇关于在哈希中查找重复的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆