python的collection系列-雙向隊列和單向隊列

單向隊列:數據先進先出app

雙向隊列:可進可出ide

雙向隊列部分源碼:ui

 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         pass
10 
11     def appendleft(self, *args, **kwargs): # real signature unknown
12         """ Add an element to the left side of the deque. """
13         pass
14 
15     def clear(self, *args, **kwargs): # real signature unknown
16         """ Remove all elements from the deque. """
17         pass
18 
19     def count(self, value): # real signature unknown; restored from __doc__
20         """ D.count(value) -> integer -- return number of occurrences of value """
21         return 0 22 
23     def extend(self, *args, **kwargs): # real signature unknown
24         """ Extend the right side of the deque with elements from the iterable """
25         pass
26 
27     def extendleft(self, *args, **kwargs): # real signature unknown
28         """ Extend the left side of the deque with elements from the iterable """
29         pass
30 
31     def pop(self, *args, **kwargs): # real signature unknown
32         """ Remove and return the rightmost element. """
33         pass
34 
35     def popleft(self, *args, **kwargs): # real signature unknown
36         """ Remove and return the leftmost element. """
37         pass
38 
39     def remove(self, value): # real signature unknown; restored from __doc__
40         """ D.remove(value) -- remove first occurrence of value. """
41         pass
42 
43     def reverse(self): # real signature unknown; restored from __doc__
44         """ D.reverse() -- reverse *IN PLACE* """
45         pass
46 
47     def rotate(self, *args, **kwargs): # real signature unknown
48         """ 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())      #清空隊列,返回None
11 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 2
26 None
27 deque(['kk1', 'h1h', 'r1r', 'rr', 'hh', 'kk'])
28 kk
29 kk1
30 deque(['h1h', 'r1r', 'hh'])
31 deque(['hh', 'r1r', 'h1h'])
32 deque(['h1h', 'hh', 'r1r'])

單向隊列部分源碼:spa

 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 Empty 102  self.not_empty.wait(remaining) 103             item = self._get() 104  self.not_full.notify() 105             return item 106 
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. Otherwise 119  raise the Empty exception. 120         '''
121         return self.get(block=False) 122 
123     # Override these methods to implement other queue organizations
124     # (e.g. stack or priority queue).
125     # These will only be called with appropriate locks held
126 
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 2
11 123
相關文章
相關標籤/搜索