一入python深似海--dict(字典)的一种实现
以下是python中字典的一种实现。用list数据结构实现字典。详细是这种:[[(key1,value1),(key2,value2),...],[],[],...]
内部每个hash地址是一个list,存放hash地址同样的(key,value)对。
dict代码
def Map(num_buckets=256):
"""Initializes a Map with the given number of buckets."""
aMap = []
for i in range(0, num_buckets):
aMap.append([])
return aMap def Map_hash(aMap, key):
"""Given a key this will create a number and then convert it to
and index for the aMap's buckets."""
return hash(key) % len(aMap) def Map_get_bucket(aMap, key):
"""Given a key, find the bucket where it would go."""
bucket_id = Map_hash(aMap, key)
return aMap[bucket_id] def Map_get_slot(aMap, key, default=None):
"""Returns the index, key, and value of a slot found in a bucket."""
bucket = Map_get_bucket(aMap, key) for i, kv in enumerate(bucket):#bucket=[[k1,v1],[k2,v2],...]
k, v = kv
if key == k:
return i, k, v#ex1:i=0,k=k1,v=v1 return -1, key, default def Map_get(aMap, key, default=None):
"""Gets the value in a bucket for the given key, or the default."""
i, k, v = Map_get_slot(aMap, key, default=default)
return v def Map_set(aMap, key, value):
"""Sets the key to the value, replacing any existing value."""
bucket = Map_get_bucket(aMap, key)
i, k, v = Map_get_slot(aMap, key) if v:
bucket[i] = (key, value)#key/value pair
else:
bucket.append((key, value)) def Map_delete(aMap, key):
"""Deletes the given key from the Map."""
bucket = Map_get_bucket(aMap, key) for i in xrange(len(bucket)):
k, v = bucket[i]
if key == k:
del bucket[i]
break def Map_list(aMap):
"""Prints out what's in the Map."""
for bucket in aMap:
if bucket:
for k, v in bucket:
print k, v # The tests that it will work. jazz = Map()
Map_set(jazz, 'Miles Davis', 'Flamenco Sketches')
# confirms set will replace previous one
Map_set(jazz, 'Miles Davis', 'Kind Of Blue')
Map_set(jazz, 'Duke Ellington', 'Beginning To See The Light')
Map_set(jazz, 'Billy Strayhorn', 'Lush Life') print "---- List Test ----"
Map_list(jazz) print "---- Get Test ----"
print Map_get(jazz, 'Miles Davis')
print Map_get(jazz, 'Duke Ellington')
print Map_get(jazz, 'Billy Strayhorn') print "---- Delete Test ----"
print "** Goodbye Miles"
Map_delete(jazz, "Miles Davis")
Map_list(jazz) print "** Goodby Duke"
Map_delete(jazz, "Duke Ellington")
Map_list(jazz) print "** Goodbye Billy"
Map_delete(jazz, "Billy Strayhorn")
Map_list(jazz) print "** Goodbye Pork Pie Hat"
Map_delete(jazz, "Charles Mingus")
Map_hash()函数的解释例如以下:
a number. Python uses this function for its own dict data structure, and I'm just reusing it. You should fire up a Python console to see how it works. Once I have a number for the key, I then use the % (modulus)
operator and thelen(aMap) to get a bucket where this key can go. As you should know, the % (modulus)
operator will divide any number and give me the remainder. I can also use this as a way of limiting giant numbers to a fixed smaller set of other numbers. If you don't get this then use Python to explore it.
一入python深似海--dict(字典)的一种实现的更多相关文章
- 一入python深似海--浅拷贝与深拷贝
python中有一个模块copy,deepcopy函数用于深拷贝,copy函数用于浅拷贝. 要理解浅拷贝,必须先弄清楚python中的引用. 引用 Python中一切都是对象,变量中存放的是对象的引用 ...
- 一入python深似海--对象的属性
Python中一切皆是对象,每一个对象都能够有多个属性.Python是怎样管理这些属性呢?我们来探讨一下. 属性的__dict__系统 对象的属性包括两部分:类属性和对象属性.对象的属性可能来自于其类 ...
- 一入python深似海--class
python class 分为三个部分:class and object(类与对象),inheritance(继承),overload(重载)and override(覆写). class and o ...
- 一入python深似海--变量和对象
一.基本原理 Python中一切都是对象,变量是对象的引用. 这是一个普遍的法则.我们举个样例来说.Python是怎样来处理的. x = 'blue' y = 'green' z = x 当pytho ...
- 一入python深似海--range()、list与for
range使用方法 使用python的人都知道range()函数非常方便,今天再用到他的时候发现了非常多曾经看到过可是忘记的细节. 这里记录一下: range(1,5)#代表从1到5(不包括5) [1 ...
- 一入python深似海--python之道
python社区不乏幽默.先来看"python之道"这首诗. 导入this包: import this 输出是一首诗,这首诗总结了Python的风格,能够指导Python程序猿的编 ...
- 一入Python深似海--print
先给大家来个干货^~^,学习Python的一个好站点,http://learnpythonthehardway.org/book/ 经典样例 以下是几个老经典的样例喽,刚接触Python的能够敲一敲, ...
- 「一入 Java 深似海 」系列课程
第一期 「一入 Java 深似海 」系列课程 - 第一期 第一节:Java 语言基础
- 一入爬虫深似海,从此游戏是路人!总结我的python爬虫学习笔记!
前言 还记得是大学2年级的时候,偶然之间看到了学长在学习python:我就坐在旁边看他敲着代码,感觉很好奇.感觉很酷,从那之后,我就想和学长一样的厉害,就想让学长教我,请他吃了一周的饭,他答应了.从此 ...
随机推荐
- 【Android】以BaseAdapter做适配器的ListView及其性能优化
适配器的Java类 package com.app.adapter; import org.json.JSONArray; import org.json.JSONObject; import and ...
- HDU 4749-Parade Show(KMP变形)
题意: 给出一个母串和一个模式串求母串中最多能分成最大的子串数(每个字串中的各个数字的大小关系和模式串相同) 分析: KMP变形匹配规则变一下即可,用当前数字和下个数字的差表示,大小关系方便匹配 #i ...
- 【Windows核心编程】VirtualAlloc 例子
// VirtualAlloc.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <Windows.h> #in ...
- SQL数据库面试题以及答案
Student(stuId,stuName,stuAge,stuSex) 学生表 stuId:学号:stuName:学生姓名:stuAge:学生年龄:stuSex:学生性别 Course(course ...
- Struts2的输入验证
一.概述: ① Struts2的输入验证 –基于 XWorkValidation Framework的声明式验证:Struts2提供了一些基于 XWork Validation Framework的内 ...
- codeforces 624B Making a String
Making a String time limit per test 1 second memory limit per test 256 megabytes input standard inpu ...
- java封装对象转json字符串
/** * Copyright (c) 2011-2015, James Zhan 詹波 (jfinal@126.com). * * Licensed under the Apache License ...
- ios页面传值的几种方法
1.属性2.方法3.代理方法4.SharedApplication5.NSUserdefault6.通过一个单例的class来传递 属性这种方法传值挺方便的,只需要拿到它的指针,如果重新声明一个指针, ...
- HDU2066一个人的旅行(dijkstra)
一开始拿到这个题感觉floyd可能会超,还是写了写,果然1WA+1TLE,之后觉得用dijkstra试试看看S和D会不会比较小,还是1WA+1TLE,最后还是借鉴了别人的做法. 把他的家作为起点,与他 ...
- LCA算法
LCA算法: LCA(Least Common Ancestor),顾名思义,是指在一棵树中,距离两个点最近的两者的公共节点.也就是说,在两个点通往根的道路上,肯定会有公共的节点,我们就是要求找到公共 ...