Python collections模块详解之——OderedDict

基本信息

collections模块实现了一些特殊的容器类型,用作Python内置的通用容器dict,list,set和tuple的补充.本次介绍的OrderedDict模块是dict的子类,它会记录值放入的顺序.
在python3.1之后添加了如下新的功能:

  • popitem(last=True):
    该方法返回并删除一对键值.如果last为True(默认值),则为LIFO(后进先出);否则为FIFO(先进先出).
  • move_to_end(key, last=True):
    将现有的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和其他诸如普通的dictmapping类对象比较时,是顺序不敏感的.

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

使用OrderedDict实现LRUcache

这也是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)])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值