collections模块实现了一些特殊的容器类型,用作Python内置的通用容器dict,list,set和tuple的补充.本次介绍的OrderedDict模块是dict的子类,它会记录值放入的顺序.
在python3.1之后添加了如下新的功能:
popitem(last=True)
:move_to_end(key, last=True)
:同是OderedDict,顺序不同,则不相等.也就是当同是OrderedDict时,相等判断是顺序敏感的.
from collections import OrderedDict
od1, od2 = OrderedDict(), OrderedDict()
od1['a'] = 1
od1['b'] = 2
od1['c'] = 3
od2['b'] = 2
od2['a'] = 1
od2['c'] = 3
print(f'od1:{od1.items()}')
print(f'od2:{od2.items()}')
print(f'od1 == od2: {od1 == od2}')
od1:odict_items([('a', 1), ('b', 2), ('c', 3)])
od2:odict_items([('b', 2), ('a', 1), ('c', 3)])
od1 == od2: False
print(od1.get('d'))
None
如果是OrderedDict和其他诸如普通的dict
的mapping类对象比较时,是顺序不敏感的.
d1 = {}
d1['a'] = 1
d1['b'] = 2
d1['c'] = 3
print(f'd1:{d1.items()}')
print(f'od1 == d1: {od1 == d1}')
print(f'od2 == d1: {od2 == d1}')
d1:dict_items([('a', 1), ('b', 2), ('c', 3)])
od1 == d1: True
od2 == d1: True
这也是LeetCode的141题
class LRUCache:
def __init__(self, capacity: int):
from collections import OrderedDict
self.cache = OrderedDict()
self.maxsize = capacity
def get(self, key: int) -> int:
res = self.cache.get(key)
if not res:
res = -1
else:
self.cache.move_to_end(key)
return res
def put(self, key: int, value: int) -> None:
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.maxsize:
self.cache.popitem(last=False)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
obj = LRUCache(2)
obj.put(2,1)
print(obj.cache.items())
obj.put(1,1)
print(obj.cache.items())
obj.put(2,3)
print(obj.cache.items())
obj.put(4,1)
print(obj.get(1))
print(obj.cache.items())
print(obj.get(2))
print(obj.cache.items())
odict_items([(2, 1)])
odict_items([(2, 1), (1, 1)])
odict_items([(1, 1), (2, 3)])
-1
odict_items([(2, 3), (4, 1)])
3
odict_items([(4, 1), (2, 3)])