collections
namedtuple
定义数据类型,使数据类型更有可读性
Point = namedtuple('Point', ['x', 'y'])
# 实例化
p = Point(11, y=22)
# 像list一样访问
p[0] + p[1]
# 像dict一样方法
p.x + p.y
defaultdict
指定字典类型value的默认值
# 指定value为list
brands = collections.defaultdict(list)
for rid, brand in mget_restaurant_brands(restaurant_ids).items():
if brand.id is None:
continue
brands[brand.id].append(rid)
# 指定为dict
restaurantid_foods = collections.defaultdict(dict)
for index, item in enumerate(result):
restaurantid_foods[index][item['id']] = item['name']
# 指定为int
counter = collections.defaultdict(int)
# 可以直接进行加法运算
counter[index] += 1
OrderedDict
有序字典
class LRU(OrderedDict):
'Limit size, evicting the least recently looked-up key when full'
def __init__(self, maxsize=128, *args, **kwds):
self.maxsize = maxsize
super().__init__(*args, **kwds)
def __getitem__(self, key):
value = super().__getitem__(key)
self.move_to_end(key)
return value
def __setitem__(self, key, value):
super().__setitem__(key, value)
if len(self) > self.maxsize:
oldest = next(iter(self))
del self[oldest]