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

单向队列:数据先进先出

双向队列:可进可出

双向队列部分源码:

 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
时间: 2024-10-18 05:31:37

python的collection系列-双向队列和单向队列的相关文章

Python之collection系列

1.计数器(counter) Counter是对字典类型的补充,用于追踪值出现的次数. 提示:具备字典的所有功能和自己地功能 示例① collections c1 =collections.Counter() c1 运行结果: D:\Python27\python.exe C:/Users/ryan/PycharmProjects/s11day3/coll.pyCounter({'c': 4, 'd': 4, 'q': 4, 'a': 3, 'f': 3, 'e': 2}) 常见方法: >>&

python的collection系列-可命名元组(namedtuple)

1 import collections 2 #创建类 3 MytupleClass = collections.namedtuple("MytupleClass",["x","y","z"]) 4 obj = MytupleClass(11,22,33) 5 print(obj.x) 6 print(obj.y) 7 print(obj.z) #应用于坐标 8 #print(help(MytupleClass)) #查看创建

python的collection系列-counter

一.计数器(counter) Counter是对字典类型的补充,用于追踪值的出现次数. 具备字典的所有功能 + 自己的功能. 1 import collections 2 aa = collections.Counter("sdfdsgsdf;sdfssfd") #把所有元素出现的次数统计下来了 3 print(aa) 4 5 输出结果: 6 Counter({'s': 6, 'd': 5, 'f': 4, ';': 1, 'g': 1}) 部分源码分析: 1 def most_com

python的collection系列-有序字典(OrderedDict)

orderdDict是对字典类型的补充,他记住了字典元素添加的顺序 注意:字典默认循环只输出key 1 import collections 2 dic = collections.OrderedDict() 3 dic["k1"] = "v1" 4 dic["k2"] = "v2" 5 dic["k3"] = "v3" 6 print(dic) 7 #实现原理:相当于用列表(有序)来维

Python学习笔记-Day03 -第二部分(双向队列-deque和单向队列Queue)

双向队列 线程安全的双向队列 例 >>> a= collections.deque() >>> a.append(1) >>> a.appendleft(2) >>> a.append(3) >>> a.appendleft(4) >>> a.append(5) >>> a.appendleft(6) >>> a deque([6, 4, 2, 1, 3, 5])

python学习笔记4:基础(集合,collection系列,深浅拷贝)

转载至:http://www.cnblogs.com/liu-yao/p/5146505.html 一.集合 1.集合(set): 把不同的元素组成一起形成集合,是python基本的数据类型.集合元素(set elements):组成集合的成员 python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)

3.python基础补充(集合,collection系列,深浅拷贝)

一.集合 1.集合(set): 把不同的元素组成一起形成集合,是python基本的数据类型.集合元素(set elements):组成集合的成员 python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算. sets 支持 x in set, len(set),和 for x in set.作

Python 从零学起(纯基础) 笔记 之 collection系列

Collection系列  1.  计数器(Counter) Counter是对字典类型的补充,用于追踪值的出现次数   ps  具备字典所有功能 + 自己的功能 Counter 1 import collections 2 obj = collections.Counter('haskhflajgahg') 3 print(obj) 4 ret = obj.most_common(4)#取前四位(很少用到) 5 print(ret) 结果: Counter({'a': 3, 'h': 3, '

STL系列之三 queue 单向队列

queue单向队列与栈有点类似,一个是在同一端存取数据,另一个是在一端存入数据,另一端取出数据.单向队列中的数据是先进先出(First In First Out,FIFO).在STL中,单向队列也是以别的容器作为底部结构,再将接口改变,使之符合单向队列的特性就可以了.因此实现也是非常方便的.下面就给出单向队列的函数列表和VS2008中单向队列的源代码.单向队列一共6个常用函数(front().back().push().pop().empty().size()),与栈的常用函数较为相似. VS2