python的collection系列-双向队列和单向队列
2016-04-23 00:06
489 查看
单向队列:数据先进先出
双向队列:可进可出
双向队列部分源码:
单向队列部分源码:
双向队列:可进可出
双向队列部分源码:
class deque(object): """ deque([iterable[, maxlen]]) --> deque object Build an ordered collection with optimized access from its endpoints. """ def append(self, *args, **kwargs): # real signature unknown """ Add an element to the right side of the deque. """ pass def appendleft(self, *args, **kwargs): # real signature unknown """ Add an element to the left side of the deque. """ pass def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from the deque. """ pass def count(self, value): # real signature unknown; restored from __doc__ """ D.count(value) -> integer -- return number of occurrences of value """ return 0 def extend(self, *args, **kwargs): # real signature unknown """ Extend the right side of the deque with elements from the iterable """ pass def extendleft(self, *args, **kwargs): # real signature unknown """ Extend the left side of the deque with elements from the iterable """ pass def pop(self, *args, **kwargs): # real signature unknown """ Remove and return the rightmost element. """ pass def popleft(self, *args, **kwargs): # real signature unknown """ Remove and return the leftmost element. """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ D.remove(value) -- remove first occurrence of value. """ pass def reverse(self): # real signature unknown; restored from __doc__ """ D.reverse() -- reverse *IN PLACE* """ pass def rotate(self, *args, **kwargs): # real signature unknown """ Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. """ pass
#练习验证 import collections aa = collections.deque() #双向队列 aa.append("1") #在右边添加 aa.appendleft("10") #在左边添加 aa.appendleft("1") bb = aa.count("1") #统计指定字符出现的次数 print(aa) print(bb) print(aa.clear()) #清空队列,返回None aa.extend(["rr","hh","kk"]) #向右扩展 aa.extendleft(["r1r","h1h","kk1"]) #向左扩展 print(aa) print(aa.pop()) #不加参数默认移除最后一个, print(aa.popleft()) #不加参数默认移除最左边一个 aa.remove('rr') #移除指定值 print(aa) aa.reverse() print(aa) #翻转 aa.rotate(1) #把后面的几个移到前面去 print(aa) #执行结果: deque(['1', '10', '1']) 2 None deque(['kk1', 'h1h', 'r1r', 'rr', 'hh', 'kk']) kk kk1 deque(['h1h', 'r1r', 'hh']) deque(['hh', 'r1r', 'h1h']) deque(['h1h', 'hh', 'r1r'])
单向队列部分源码:
def join(self): '''Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. ''' with self.all_tasks_done: while self.unfinished_tasks: self.all_tasks_done.wait() def qsize(self): '''Return the approximate size of the queue (not reliable!).''' with self.mutex: return self._qsize() def empty(self): '''Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0 as a direct substitute, but be aware that either approach risks a race condition where a queue can grow before the result of empty() or qsize() can be used. To create code that needs to wait for all queued tasks to be completed, the preferred technique is to use the join() method. ''' with self.mutex: return not self._qsize() def full(self): '''Return True if the queue is full, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() >= n as a direct substitute, but be aware that either approach risks a race condition where a queue can shrink before the result of full() or qsize() can be used. ''' with self.mutex: return 0 < self.maxsize <= self._qsize() def put(self, item, block=True, timeout=None): '''Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case). ''' with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 self.not_empty.notify() def get(self, block=True, timeout=None): '''Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). ''' with self.not_empty: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while not self._qsize(): remaining = endtime - time() if remaining <= 0.0: raise Empty self.not_empty.wait(remaining) item = self._get() self.not_full.notify() return item def put_nowait(self, item): '''Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available. Otherwise raise the Full exception. ''' return self.put(item, block=False) def get_nowait(self): '''Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception. ''' return self.get(block=False) # Override these methods to implement other queue organizations # (e.g. stack or priority queue). # These will only be called with appropriate locks held # Initialize the queue representation
#练习 import queue q = queue.Queue() q.put("123") #加入队列 q.put("345") print(q.qsize()) #计算加入队列的数据个数 print(q.get()) #取队列数据(先进先出) #执行结果 2 123
相关文章推荐
- 一键搞定python连接mysql驱动有关问题(windows版本)
- Python 探针的实现原理
- Python 中的 else详解
- Python的 循环器 itertools
- python super方法
- python 单例
- python爬虫开发–实战百度招聘(json包的处理)
- Python2.7爬虫练习爬百度百科python词条
- (转载)Python学习–数据分析路线
- Python Challenge
- python中的实例方法、静态方法、类方法、类变量和实例变量
- python的collection系列-可命名元组(namedtuple)
- python中的函数
- python之pandas的使用:数据的导入技巧
- python爬虫
- Python中Matplotlib绘图
- Python调试
- LeetCode[Design]----Peeking Iterator
- 使用python字典合并文本
- VScode编写第一个Python程序HelloWorld