3

《Fluent Python》 读书笔记:字典和集合

 2 years ago
source link: https://www.lfhacks.com/tech/python-fluent-dict-set/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
扫一扫,转发文章

dict 类型是 Python 语言的基石。

正因为 dict 类型至关重要,Python 对它的实现做了高度优化。性能出众的原因在于使用了散列表(或者叫哈希表),另外,set 类型也依赖散列表。

这篇文章 对比了 hashable 和 immutable 的概念。

用户自定义类型

一般来讲,用户自定义的类型的对象都是可散列(hashable)的,散列值就是对象的 id() 函数返回值。

>>> class A:... pass... >>> a=A()>>> id(a)2310136739536>>> b=A() >>> id(b) 2310138637664>>> a==bFalse

setdefault 方法

虽然 dict.get(key, default) 可以给不存在的键一个默认的返回值,但是在有些场景下,这种方法不是很自然。比如:

统计每个单词出现的频率,当循环到某个从未出现过的单词时。就会有下面这种写法。

occurrences = index.get(word, [])occurrences.append(...)index[word] = occurrences

每次循环中,对于每一个词 word ,在 index 中要查询两次。

如果用setdefault,写法是这样:

index.setdefault(word, []).append(...)

defaultdict 方法

为了进一步的方便,还希望对于不存在的键,能得到一个默认值。可以借助 collections.defaultdict,详细的介绍在 这篇文档

__missing__ 的例子

希望有这么一个字典,名叫 StrKeyDict,key 既能用字符串类型,也能用对应的数字,比如:

>>> d=StrKeyDict(['2', 'two'], ['4', 'four'])>>> d['2']'two'>>> d[2]'two'>>> d[1]KeyError: '1'

为了实现这个功能,需要自定义一个映射类型,从原始类型 dict 派生而来。

class StrKeyDict(dict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] ...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK