我如何使用哈希表(这可能吗?)来查询属于同一对象的多个参数?
让我解释一下。
如果我有以下对象数组
persons = [{name: "AA"}, {name: "BB"}, {name: "CA"}]
我想将它们存储在哈希表中,使用 name
作为 value
hashtable.put(persons[0]); // will compute hash("AA")
hashtable.put(persons[1]); // will compute hash("BB")
hashtable.put(persons[2]); // will compute hash("CA")
这将使我能够非常快速地通过 name
查询我的哈希表。
我的问题是,是否有任何哈希表的实现允许我为更复杂的对象查询多个参数
persons = [{name: "AA", city: "XX"}, {name: "BB", city: "YY"}, {name: "CA", city: "ZZ"}]
例如。寻找 names = "AA"
和 cities = "ZZ"
如果哈希表不适合此类操作,哪种算法或数据结构最适合此类操作?
最佳答案
在 python 中,您可以使用 tuples
作为 hashmap 中的 keys
:
persons = [{name: "AA", city: "XX"}, {name: "BB", city: "YY"}, {name: "CA", city: "ZZ"}]
hashmap = {}
for d in persons:
hashmap[(d["name"], d["city"])] = ...
然后你可以像这样查询你的hashmap:
hashmap[(name, city)]
在其他语言中,您应该能够实现类似的功能(使用元素组作为键)。这可能需要 implementing a custom hash ,但 HashMap 仍然是正确的数据结构。
关于algorithm - 我如何使用散列映射来查询多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54469081/