• 笨办法学习python之hashmap


     1 #!/user/bin/env python
     2 #-*-coding:utf-8 -*-
     3 #Author: qinjiaxi
     4 #初始化aMap列表,把列表num_buckets添加到aMap中,num_bukets用来存hashmap里设置的内容
     5 def new(num_buckets = 256):
     6     """Initializes a map with the given number of buckets."""
     7     aMap = []
     8     for i in range(0, num_buckets):
     9         aMap.append([])
    10     return aMap
    11 def hash_key(aMap, key):
    12     """Given a key this will create a number and then convert it to an index for the aMap's buckets."""
    13     return hash(key) % len(aMap)#利用求余(模除)来获得一个放置key的位置,其中hash()函数是用来获取一个数字或者字符串的哈希值(是一个整数)。
    14 def get_bucket(aMap, key):
    15     """Given a key , find the bucket where it would go ."""
    16     bucket_id = hash_key(aMap, key)
    17     return  aMap[bucket_id]#通过bucket_id获取bucket
    18 #使用enumerate()和for循环遍历bucket,用key获取索引、键、值
    19 def get_slot(aMap, key, default = None):
    20     """
    21     Returns the index, key, and value of a slot found in a slot found in a bucket.
    22     Returns -1, key, and default(None if not set) when not found.
    23     """
    24     bucket = get_bucket(aMap, key)
    25     for i, kv in enumerate(bucket):
    26         k, v = kv
    27         if key == k:
    28             return i, k ,v
    29     return -1, key, default
    30 #取值
    31 def get(aMap, key ,default = None):
    32     """Gets the value in  a bucket for the given key, or the default."""
    33     i, k, v = get_slot(aMap, key, default = None)
    34     return v
    35 #设置键值对追加到字典中,保证每个key存储一次
    36 def set(aMap, key, value):
    37     """Set the key to the value, replacing any existing value."""
    38     bucket = get_bucket(aMap, key)
    39     i, k, v = get_slot(aMap, key)
    40 #如果位置存在就代替
    41     if i >= 0:
    42         #the key exists, replace it
    43         bucket[i] = (key, value)
    44 #不存在就追加到字典中
    45     else:
    46         #the key does not ,append to creat it
    47         bucket.append((key, value))
    48 #通过key删除bucket
    49 def delete(aMap, key):
    50     """ Deletes the given key from the Map."""
    51     bucket = get_bucket(aMap, key)
    52     for i in range(len(bucket)):
    53         k, v = bucket[i]
    54         if key == k:
    55             del bucket[i]
    56             break
    57 #调试打印hashmap功能
    58 def list(aMap):
    59     """Prints out what's in the Map"""
    60     for bucket in aMap:
    61         if bucket:
    62             for k,v in bucket:
    63                 print (k, v)
  • 相关阅读:
    BZOJ 3105: [cqoi2013]新Nim游戏
    informatica增量抽取图文
    informatica ETL增量抽取(时间戳)
    kafka connector 使用总结以及自定义connector开发(×××××)
    Kafka Connect JDBC-Source 源连接器配置属性
    kafka-connect-jdbc-sink配置属性
    得到自1970年1月1日以来的秒数
    kafka-connect-jdbc(重要)
    confluent kafka-connect-jdbc(非常重要)
    kafka集群版 connectors 通过REST API实现控制
  • 原文地址:https://www.cnblogs.com/qinlangsky/p/9417736.html
Copyright © 2020-2023  润新知