码迷,mamicode.com
首页 > 编程语言 > 详细

python的collection系列-双向队列和单向队列

时间:2016-04-23 01:22:18      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

单向队列:数据先进先出

双向队列:可进可出

双向队列部分源码:

 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])

单向队列部分源码:

  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

 

python的collection系列-双向队列和单向队列

标签:

原文地址:http://www.cnblogs.com/repo/p/5423353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!