博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python的collection系列-双向队列和单向队列
阅读量:5155 次
发布时间:2019-06-13

本文共 8479 字,大约阅读时间需要 28 分钟。

单向队列:数据先进先出

双向队列:可进可出

双向队列部分源码:

1 class deque(object): 2     """ 3     deque([iterable[, maxlen]]) --> deque object 4      5     Build an ordered collection with optimized access from its endpoints. 6     """ 7     def append(self, *args, **kwargs): # real signature unknown 8         """ Add an element to the right side of the deque. """ 9         pass10 11     def appendleft(self, *args, **kwargs): # real signature unknown12         """ Add an element to the left side of the deque. """13         pass14 15     def clear(self, *args, **kwargs): # real signature unknown16         """ Remove all elements from the deque. """17         pass18 19     def count(self, value): # real signature unknown; restored from __doc__20         """ D.count(value) -> integer -- return number of occurrences of value """21         return 022 23     def extend(self, *args, **kwargs): # real signature unknown24         """ Extend the right side of the deque with elements from the iterable """25         pass26 27     def extendleft(self, *args, **kwargs): # real signature unknown28         """ Extend the left side of the deque with elements from the iterable """29         pass30 31     def pop(self, *args, **kwargs): # real signature unknown32         """ Remove and return the rightmost element. """33         pass34 35     def popleft(self, *args, **kwargs): # real signature unknown36         """ Remove and return the leftmost element. """37         pass38 39     def remove(self, value): # real signature unknown; restored from __doc__40         """ D.remove(value) -- remove first occurrence of value. """41         pass42 43     def reverse(self): # real signature unknown; restored from __doc__44         """ D.reverse() -- reverse *IN PLACE* """45         pass46 47     def rotate(self, *args, **kwargs): # real signature unknown48         """ Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left. """49         pass
1 #练习验证 2 import collections 3 aa = collections.deque()    #双向队列 4 aa.append("1")       #在右边添加 5 aa.appendleft("10")   #在左边添加 6 aa.appendleft("1") 7 bb = aa.count("1")     #统计指定字符出现的次数 8 print(aa) 9 print(bb)10 print(aa.clear())      #清空队列,返回None11 aa.extend(["rr","hh","kk"])     #向右扩展12 aa.extendleft(["r1r","h1h","kk1"])    #向左扩展13 print(aa)14 print(aa.pop())     #不加参数默认移除最后一个,15 print(aa.popleft())   #不加参数默认移除最左边一个16 aa.remove('rr')     #移除指定值17 print(aa)18 aa.reverse()19 print(aa)      #翻转20 aa.rotate(1)    #把后面的几个移到前面去21 print(aa)22 23 #执行结果:24 deque(['1', '10', '1'])25 226 None27 deque(['kk1', 'h1h', 'r1r', 'rr', 'hh', 'kk'])28 kk29 kk130 deque(['h1h', 'r1r', 'hh'])31 deque(['hh', 'r1r', 'h1h'])32 deque(['h1h', 'hh', 'r1r'])

单向队列部分源码:

1 def join(self):  2         '''Blocks until all items in the Queue have been gotten and processed.  3   4         The count of unfinished tasks goes up whenever an item is added to the  5         queue. The count goes down whenever a consumer thread calls task_done()  6         to indicate the item was retrieved and all work on it is complete.  7   8         When the count of unfinished tasks drops to zero, join() unblocks.  9         ''' 10         with self.all_tasks_done: 11             while self.unfinished_tasks: 12                 self.all_tasks_done.wait() 13  14     def qsize(self): 15         '''Return the approximate size of the queue (not reliable!).''' 16         with self.mutex: 17             return self._qsize() 18  19     def empty(self): 20         '''Return True if the queue is empty, False otherwise (not reliable!). 21  22         This method is likely to be removed at some point.  Use qsize() == 0 23         as a direct substitute, but be aware that either approach risks a race 24         condition where a queue can grow before the result of empty() or 25         qsize() can be used. 26  27         To create code that needs to wait for all queued tasks to be 28         completed, the preferred technique is to use the join() method. 29         ''' 30         with self.mutex: 31             return not self._qsize() 32  33     def full(self): 34         '''Return True if the queue is full, False otherwise (not reliable!). 35  36         This method is likely to be removed at some point.  Use qsize() >= n 37         as a direct substitute, but be aware that either approach risks a race 38         condition where a queue can shrink before the result of full() or 39         qsize() can be used. 40         ''' 41         with self.mutex: 42             return 0 < self.maxsize <= self._qsize() 43  44     def put(self, item, block=True, timeout=None): 45         '''Put an item into the queue. 46  47         If optional args 'block' is true and 'timeout' is None (the default), 48         block if necessary until a free slot is available. If 'timeout' is 49         a non-negative number, it blocks at most 'timeout' seconds and raises 50         the Full exception if no free slot was available within that time. 51         Otherwise ('block' is false), put an item on the queue if a free slot 52         is immediately available, else raise the Full exception ('timeout' 53         is ignored in that case). 54         ''' 55         with self.not_full: 56             if self.maxsize > 0: 57                 if not block: 58                     if self._qsize() >= self.maxsize: 59                         raise Full 60                 elif timeout is None: 61                     while self._qsize() >= self.maxsize: 62                         self.not_full.wait() 63                 elif timeout < 0: 64                     raise ValueError("'timeout' must be a non-negative number") 65                 else: 66                     endtime = time() + timeout 67                     while self._qsize() >= self.maxsize: 68                         remaining = endtime - time() 69                         if remaining <= 0.0: 70                             raise Full 71                         self.not_full.wait(remaining) 72             self._put(item) 73             self.unfinished_tasks += 1 74             self.not_empty.notify() 75  76     def get(self, block=True, timeout=None): 77         '''Remove and return an item from the queue. 78  79         If optional args 'block' is true and 'timeout' is None (the default), 80         block if necessary until an item is available. If 'timeout' is 81         a non-negative number, it blocks at most 'timeout' seconds and raises 82         the Empty exception if no item was available within that time. 83         Otherwise ('block' is false), return an item if one is immediately 84         available, else raise the Empty exception ('timeout' is ignored 85         in that case). 86         ''' 87         with self.not_empty: 88             if not block: 89                 if not self._qsize(): 90                     raise Empty 91             elif timeout is None: 92                 while not self._qsize(): 93                     self.not_empty.wait() 94             elif timeout < 0: 95                 raise ValueError("'timeout' must be a non-negative number") 96             else: 97                 endtime = time() + timeout 98                 while not self._qsize(): 99                     remaining = endtime - time()100                     if remaining <= 0.0:101                         raise Empty102                     self.not_empty.wait(remaining)103             item = self._get()104             self.not_full.notify()105             return item106 107     def put_nowait(self, item):108         '''Put an item into the queue without blocking.109 110         Only enqueue the item if a free slot is immediately available.111         Otherwise raise the Full exception.112         '''113         return self.put(item, block=False)114 115     def get_nowait(self):116         '''Remove and return an item from the queue without blocking.117 118         Only get an item if one is immediately available. Otherwise119         raise the Empty exception.120         '''121         return self.get(block=False)122 123     # Override these methods to implement other queue organizations124     # (e.g. stack or priority queue).125     # These will only be called with appropriate locks held126 127     # Initialize the queue representation
1 #练习 2 import queue 3 q = queue.Queue() 4 q.put("123")    #加入队列 5 q.put("345") 6 print(q.qsize())   #计算加入队列的数据个数 7 print(q.get())     #取队列数据(先进先出) 8  9 #执行结果10 211 123

 

转载于:https://www.cnblogs.com/repo/p/5423353.html

你可能感兴趣的文章
python-变量
查看>>
507 Perfect Number 完美数
查看>>
前端资源链接汇总
查看>>
排序和查找
查看>>
多次查询一段区间内有多少个子区间满足其中一个端点为区间最大值。
查看>>
mongodb 按照时间聚类 java
查看>>
易飞90设计自己定义画面新增功能说明
查看>>
python xlrd
查看>>
GIT的使用方法
查看>>
php超级全局变量
查看>>
Java字符串与字符、字节数组知识点总结
查看>>
1. Jquery简介
查看>>
最短路 || Codeforces 938D Buy a Ticket
查看>>
MAVEN,SPRING,CXF构建REST风格WebService
查看>>
How to: How to disable Java Security Warning "The application requires an earlier version of Java."
查看>>
svn的安装与配置(转载)
查看>>
uwsgi基础——SNMP
查看>>
八皇后问题
查看>>
java1.8 Stream
查看>>
day①:集合
查看>>