python 队列 一次取多个_Queue 队列模块-Python成为专业人士笔记
生活随笔
收集整理的這篇文章主要介紹了
python 队列 一次取多个_Queue 队列模块-Python成为专业人士笔记
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
“專業(yè)人士筆記”系列目錄:
創(chuàng)帆云:Python成為專業(yè)人士筆記--強(qiáng)烈建議收藏!每日持續(xù)更新!?zhuanlan.zhihu.com介紹
隊(duì)列模塊能實(shí)現(xiàn)多生產(chǎn)者、多消費(fèi)者的隊(duì)列,當(dāng)信息必須在多個(gè)線程之間安全地交換時(shí),它特別有用。
隊(duì)列模塊提供了三種類型的隊(duì)列,具體如下:
1、普通隊(duì)列 (先進(jìn)先出)
2 LifoQueue (后進(jìn)先出)
3 PriorityQueue ( 優(yōu)先級(jí)隊(duì)列, 即根據(jù)排序規(guī)則決定誰在隊(duì)頭,誰在隊(duì)尾 )
下面來一個(gè)簡單的例子:
普通隊(duì)列:
import queuequestion_queue = queue.Queue()#往隊(duì)列丟數(shù)據(jù) for x in range(1, 10):temp_dict = ('key', x)question_queue.put(temp_dict)#判斷隊(duì)列不為空時(shí),從隊(duì)列取數(shù)據(jù) while (not question_queue.empty()):item = question_queue.get()print(str(item))#從結(jié)果可以看到,先丟進(jìn)去的數(shù)據(jù),get的時(shí)候也會(huì)先彈出來,這就是普通隊(duì)列實(shí)現(xiàn) #('key', 1)('key', 2)('key', 3)('key', 4)('key', 5)('key', 6)('key', 7)('key', 8)('key', 9)lifo后進(jìn)先出隊(duì)列
import queuequestion_queue = queue.LifoQueue()#往隊(duì)列丟數(shù)據(jù) for x in range(1, 10):temp_dict = ('key', x)question_queue.put(temp_dict)#判斷隊(duì)列不為空時(shí),從隊(duì)列取數(shù)據(jù) while (not question_queue.empty()):item = question_queue.get()print(str(item))#輸出:類似于堆棧,先丟進(jìn)去的,最后彈出來('key', 9)('key', 8)('key', 7)('key', 6)('key', 5)('key', 4)('key', 3)('key', 2)('key', 1)優(yōu)先級(jí)隊(duì)列
import queuequestion_queue = queue.PriorityQueue();#往隊(duì)列丟數(shù)據(jù) for x in range(1, 10):temp_dict = (x,'test') #注意,這里和前面不一樣,是以x作為優(yōu)先級(jí)的;x值越小,則彈出時(shí)越優(yōu)先question_queue.put(temp_dict)#判斷隊(duì)列不為空時(shí),從隊(duì)列取數(shù)據(jù) while (not question_queue.empty()):item = question_queue.get()print(str(item))#輸出:(1, 'test')(2, 'test')(3, 'test')(4, 'test')(5, 'test')(6, 'test')(7, 'test')(8, 'test')(9, 'test')以上代碼均已在python3云環(huán)境中調(diào)試成功,有問題留言,請不要轉(zhuǎn)載,謝謝
總結(jié)
以上是生活随笔為你收集整理的python 队列 一次取多个_Queue 队列模块-Python成为专业人士笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓手机状态栏 定位服务自动关闭_手机该
- 下一篇: vm虚拟机下linux安装python_