import queue
q = queue.Queue()
for i in range(10):
q.put(i)
while not q.empty():
print(q.get())
0 1 2 3 4 5 6 7 8 9
0
是最先放入到队列中的,使用 get
方法时,第一个取到的数值就是 0
,
当 9
被取出来时,队列变成了空队列,程序输出结果:
0
1
2
3
4
5
6
7
8
9
import queue
q = queue.LifoQueue()
for i in range(10):
q.put(i)
while not q.empty():
print(q.get())
9 8 7 6 5 4 3 2 1 0
9最后被放入到队列中,第一个被取出来,程序输出结果:
9
8
7
6
5
4
3
2
1
0
这种数据结构有很广泛的用途,比如下面这个字符串:
string = '((sdf)sdf)(sg()())gsg((sgsg()))'
请写算法判断,字符串里的小括号是否是成对出现,使用后进先出这种数据结构,可以非常轻松的实现算法。
import queue
def is_pair(string):
q = queue.LifoQueue()
for item in string:
if item == '(':
q.put(item)
elif item == ')':
if q.empty():
return False
q.get()
return q.empty()
import queue
class Task:
def __init__(self, priority, description):
self.priority = priority
self.description = description
def __eq__(self, other):
return self.priority == other.priority
def __lt__(self, other):
return self.priority < other.priority
def __str__(self):
msg = '{_class} 优先级:{priority} 任务:{task}'
return msg.format(_class=self.__class__, priority=self.priority, task=self.description)
q = queue.PriorityQueue()
q.put(Task(3, '打游戏'))
q.put(Task(5, '做饭'))
q.put(Task(1, '洗碗'))
while not q.empty():
print(q.get())
<class '__main__.Task'> 优先级:1 任务:洗碗 <class '__main__.Task'> 优先级:3 任务:打游戏 <class '__main__.Task'> 优先级:5 任务:做饭