数据结构与算法

1.3 collections.deque

deque(maxlen=N) 新建一个固定大小的队列,如果新加入元素时队列已满,最老的元素会被除掉。

队列,插入、删除元素都是O(1)
列表/栈,在开头插入、删除元素都是O(N)

1.4 heapq

堆,适用于查找一组元素中topN的元素集合,元素个数较少。

import heapq

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

print(heapq.nlargest(3, nums))

print(heapq.nsmallest(3, nums))
portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]

cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])

1.6collections.defaultdict

字典,一个key对应多个value

from collections import defaultdict
a = defaultdict(list)
a['a'].append(1)
a['a'].append(1)
a['a'].append(2)

1.7有序列表

`collections.OrderedDict

from collections import OrderedDict
a = OrderedDict()
a[1] = 'adsf'
a['asdf'] = 111
print(a)

原理:内部有一个双向链表
空间是普通字典的两倍

你可能感兴趣的:(数据结构与算法)