核心思想是通过节节点的概念,存储每一个节点上一个节点和下一个节点的内存地址,然后每个节点中存储该节点的创建时间,每次取值判断,如果超出了自己设定的缓存时常,则清除节点。
import datetime class Node: def __init__(self,value=None,next=None,prev=None,time=None): self.value,self.next,self.prev,self.time=value,next,prev,time class Bag: def __init__(self,maxsize=None): self.root = Node() self.root.next=self.root self.root.prev=self.root self.maxsize = None self.tailnode = self.root self.headnode = self.root self.length = 0 def __len__(self): self.remove_by_time() return self.length def remove_by_time(self): curnode = self.root lis = [] while True: curnode = curnode.next if curnode == self.root: break if datetime.datetime.now() - curnode.time > datetime.timedelta(seconds=60): lis.append(curnode.value) for i in lis: self.remove(i) def append(self,value): if self.maxsize is not None and self.length>=self.maxsize: raise Exception("Full") node=Node(value=value,time=datetime.datetime.now()) if self.tailnode == self.root: self.root.next=node node.prev = self.root self.headnode=node else: node.prev=self.tailnode self.tailnode.next=node self.tailnode=node self.root.prev = node node.next = self.root self.length+=1 def appendleft(self,value): if self.maxsize is not None and self.length>=self.maxsize: raise Exception("Full") node=Node(value=value,time=datetime.datetime.now()) if self.tailnode==self.root: self.root.prev=node node.next=self.root self.tailnode=node else: node.next = self.headnode self.headnode.prev=node self.headnode = node self.root.next = node node.prev = self.root self.length+=1 def iter_node(self): curnode = self.root while True: curnode = curnode.next if curnode == self.root: break yield curnode def __iter__(self): self.remove_by_time() for i in self.iter_node(): yield i.value def remove(self,value): for i in self.iter_node(): if i.value == value: if i==self.headnode: self.headnode=i.next if i==self.tailnode: self.tailnode=i.prev i.next.prev, i.prev.next = i.prev, i.next self.length -= 1 return i return -1