Python中的哈希映射

Kir*_*hat 124 python hashmap

我想在Python中实现HashMap.我想问一个用户输入.根据他的输入,我正在从HashMap中检索一些信息.如果用户输入HashMap的键,我想检索相应的值.

如何在Python中实现此功能?

HashMap<String,String> streetno=new HashMap<String,String>();
   streetno.put("1", "Sachin Tendulkar");
   streetno.put("2", "Dravid");
   streetno.put("3","Sehwag");
   streetno.put("4","Laxman");
   streetno.put("5","Kohli")
Run Code Online (Sandbox Code Playgroud)

Ala*_*lan 218

Python字典是一种支持键值对的内置类型.

streetno = {"1": "Sachin Tendulkar", "2": "Dravid", "3": "Sehwag", "4": "Laxman", "5": "Kohli"}
Run Code Online (Sandbox Code Playgroud)

以及使用dict关键字:

streetno = dict({"1": "Sachin Tendulkar", "2": "Dravid"}) 
Run Code Online (Sandbox Code Playgroud)

要么:

streetno = {}
streetno["1"] = "Sachin Tendulkar" 
Run Code Online (Sandbox Code Playgroud)

  • 第二个例子以与以前相同的方式构建一个dict,然后复制它.另一个使用`dict`,在这个上下文中更合适,是`dict(key1 = value1,key2 = value2,...)`但是这需要键到字符串,这些字符串也是有效的Python标识符(在内部,这也创建了一个字典). (7认同)
  • 你为什么不直接告诉我字典就是 hashmap (5认同)
  • 是的,它看起来像一张“地图”,它的作用也像一张“地图”。但问题不是“Python 中的映射”而是“Python 中的哈希映射”:字典是哈希(!)映射吗? (3认同)

Chr*_*dal 21

所有你想要的(在问题最初被问到的时候)都是一个暗示.这是一个提示:在Python中,您可以使用词典.


Edw*_*win 19

它内置于Python.看字典.

根据你的例子:

streetno = {"1": "Sachine Tendulkar",
            "2": "Dravid",
            "3": "Sehwag",
            "4": "Laxman",
            "5": "Kohli" }
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样访问它:

sachine = streetno["1"]
Run Code Online (Sandbox Code Playgroud)

另外值得一提的是:它可以使用任何非可变数据类型作为键.也就是说,它可以使用元组,布尔值或字符串作为键.


tot*_*aam 15

streetno = { 1 : "Sachin Tendulkar",
            2 : "Dravid",
            3 : "Sehwag",
            4 : "Laxman",
            5 : "Kohli" }
Run Code Online (Sandbox Code Playgroud)

并检索值:

name = streetno.get(3, "default value")
Run Code Online (Sandbox Code Playgroud)

要么

name = streetno[3]
Run Code Online (Sandbox Code Playgroud)

这是使用数字作为键,在数字周围加上引号以使用字符串作为键.


unw*_*ind 12

哈希映射是内置于Python中的,它们被称为字典:

streetno = {}                        #create a dictionary called streetno
streetno["1"] = "Sachin Tendulkar"   #assign value to key "1"
Run Code Online (Sandbox Code Playgroud)

用法:

"1" in streetno                      #check if key "1" is in streetno
streetno["1"]                        #get the value from key "1"
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅文档,例如内置方法等.它们很棒,在Python程序中很常见(不出所料).


Vis*_*kar 7

这是使用python的哈希映射的实现。为简单起见,哈希映射的大小固定为16。可以轻松更改。重新哈希不在此代码范围内。

class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.next = None

class HashMap:
    def __init__(self):
        self.store = [None for _ in range(16)]
    def get(self, key):
        index = hash(key) & 15
        if self.store[index] is None:
            return None
        n = self.store[index]
        while True:
            if n.key == key:
                return n.value
            else:
                if n.next:
                    n = n.next
                else:
                    return None
    def put(self, key, value):
        nd = Node(key, value)
        index = hash(key) & 15
        n = self.store[index]
        if n is None:
            self.store[index] = nd
        else:
            if n.key == key:
                n.value = value
            else:
                while n.next:
                    if n.key == key:
                        n.value = value
                        return
                    else:
                        n = n.next
                n.next = nd

hm = HashMap()
hm.put("1", "sachin")
hm.put("2", "sehwag")
hm.put("3", "ganguly")
hm.put("4", "srinath")
hm.put("5", "kumble")
hm.put("6", "dhoni")
hm.put("7", "kohli")
hm.put("8", "pandya")
hm.put("9", "rohit")
hm.put("10", "dhawan")
hm.put("11", "shastri")
hm.put("12", "manjarekar")
hm.put("13", "gupta")
hm.put("14", "agarkar")
hm.put("15", "nehra")
hm.put("16", "gawaskar")
hm.put("17", "vengsarkar")
print(hm.get("1"))
print(hm.get("2"))
print(hm.get("3"))
print(hm.get("4"))
print(hm.get("5"))
print(hm.get("6"))
print(hm.get("7"))
print(hm.get("8"))
print(hm.get("9"))
print(hm.get("10"))
print(hm.get("11"))
print(hm.get("12"))
print(hm.get("13"))
print(hm.get("14"))
print(hm.get("15"))
print(hm.get("16"))
print(hm.get("17"))
Run Code Online (Sandbox Code Playgroud)

输出:

sachin
sehwag
ganguly
srinath
kumble
dhoni
kohli
pandya
rohit
dhawan
shastri
manjarekar
gupta
agarkar
nehra
gawaskar
vengsarkar
Run Code Online (Sandbox Code Playgroud)


Fra*_*ank 7

在Python中你会使用字典。

它是Python中非常重要并且经常使用的类型。

您可以通过以下方式轻松创建一个

name = {}
Run Code Online (Sandbox Code Playgroud)

字典有很多方法:

# add entries:
>>> name['first'] = 'John'
>>> name['second'] = 'Doe'
>>> name
{'first': 'John', 'second': 'Doe'}

# you can store all objects and datatypes as value in a dictionary
# as key you can use all objects and datatypes that are hashable
>>> name['list'] = ['list', 'inside', 'dict']
>>> name[1] = 1
>>> name
{'first': 'John', 'second': 'Doe', 1: 1, 'list': ['list', 'inside', 'dict']}
Run Code Online (Sandbox Code Playgroud)

您无法影响字典的顺序。


kre*_*eim 6

class HashMap:
    def __init__(self):
        self.size = 64
        self.map = [None] * self.size

    def _get_hash(self, key):
        hash = 0

        for char in str(key):
            hash += ord(char)
        return hash % self.size

    def add(self, key, value):
        key_hash = self._get_hash(key)
        key_value = [key, value]

        if self.map[key_hash] is None:
            self.map[key_hash] = list([key_value])
            return True
        else:
            for pair in self.map[key_hash]:
                if pair[0] == key:
                    pair[1] = value
                    return True
                else:
                    self.map[key_hash].append(list([key_value]))
                    return True

    def get(self, key):
        key_hash = self._get_hash(key)
        if self.map[key_hash] is not None:
            for pair in self.map[key_hash]: 
                if pair[0] == key:
                    return pair[1]
        return None

    def delete(self, key):
        key_hash = self._get_hash(key)

        if self.map[key_hash] is None :
            return False
        for i in range(0, len(self.map[key_hash])):
            if self.map[key_hash][i][0] == key:
                self.map[key_hash].pop(i)
                return True

    def print(self):

        print('---Phonebook---')
        for item in self.map:
            if item is not None:
                print(str(item))

h = HashMap()
Run Code Online (Sandbox Code Playgroud)


Sha*_*per 6

在这种情况下,Python Counter也是一个不错的选择:

from collections import Counter

counter = Counter(["Sachin Tendulkar", "Sachin Tendulkar", "other things"])

print(counter)
Run Code Online (Sandbox Code Playgroud)

这将返回一个字典,其中包含列表中每个元素的计数:

Counter({'Sachin Tendulkar': 2, 'other things': 1})
Run Code Online (Sandbox Code Playgroud)

  • 我不明白这是如何回答这个问题的。你在这里得到的是一个字典,其中名称是键,值是一些计数器(你从哪里获得输入列表?)。虽然问题是寻找一个哈希映射,其中唯一的键指向名称作为值。 (2认同)