前言 python对字典dict的实现做了高度优化,散列表是字典类型性能出众的根本原因
集合set的实现也依赖于散列表
泛映射类型 映射是一种关联式的容器类型,它存储了对象与对象之间的映射关系
collections.abc模块中有Mapping和MutableMapping这两个抽象基类, 它们的作用是为dict和其他类似的类型定义形式接口。非抽象映射类型一般不会直接继承这些抽象基类,它们会直接对dict或是collections.User.Dict进行扩展。这些基类的作用是作为形式化的文档,它们定义了构建一个映射类型所需要的最基本的接口 它们可以和isinstance()一起用于判断某个数据是不是广义上的映射类型:
1 2 3 4 from collections import abc t = dict() print(isinstance(t, abc.Mapping)) >>>True 可散列的数据类型 标准库里的所有映射类型都是利用dict实现的,因此它们有个共同的限制,即只有可散列的数据类型才能作为这些映射里的键key
如果一个对象是可以散列的,那么在这个对象的生命周期中,它的散列值是不变的,需要实现__hash__()方法以及__eq__()
python里可散列的类型有str, bytes, frozenset
注意list是不可散列的
元组tuple当其包含的元素都是可散列的情况下,它才可以散列
下面这个列子:
1 2 3 4 5 6 7 8 L = [x for x in range(10)] print(hash(L)) >>>TypeError: unhashable type: 'list' # 列表[30, 40]被冻结后可以被散列 t = (1, 2, frozenset([30, 40])) print(hash(t)) >>>985328935373711578 字典的多种构造方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 a = dict(one=1, two=2, three=3) b = {'one':1, 'two':2, 'three':3} c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) d = dict([('one', 1), ('two', 2), ('three', 3)]) e = dict({'three':3, 'one':1, 'two':2}) print(a) print(b) print(c) print(d) print(e) >>>{'one': 1, 'two': 2, 'three': 3} >>>{'one': 1, 'two': 2, 'three': 3} >>>{'one': 1, 'two': 2, 'three': 3} >>>{'one': 1, 'two': 2, 'three': 3} >>>{'three': 3, 'one': 1, 'two': 2} print(a==b==c==d==e) >>>True 字典推导 注意这个例子的输出…...