deque bidirectional queue
Deque can add and remove elements from both ends. The common structure is its simplified version.
Deque supports the common operations of sequences, and now for a simple example, you will find that there is no difference between a flat list:
1 ImportCollections2 3Dic=collections.deque ('ABCDEFG')4 Print 'deque=', DiC5 Print 'Length:', Len (DIC)6 Print 'Left end:', Dic[0]7 Print 'Right end:', dic[-1]8Dic.remove ('C')9 Print 'Remove (c):'Dic
Direct mapping:
is not found with the list of the same, just become deque (list), the key is some basic usage is the same, a comparison chart it is more direct:
1listtest=['a','b','C','D','e','F','g']2 Print 'listtest=', Listtest3 Print 'Length:', Len (listtest)4 Print 'Left end:', Listtest[0]5 Print 'Right end:', listtest[-1]6Listtest.remove ('C')7 Print 'Remove (c):', Listtest
or Direct mapping:
Here's a unique place to go, two-way operation. Deque is the Extend method that initializes the collection element, and you can add the binding element from "left" to the collection by Extendleft:
1 ImportCollections2d1=Collections.deque ()3D1.extend ('ABCDEFG') #可以列表元素4 Print 'Extend:', D15D1.append ('h') #只会认为是一个元素加入6 Print 'Append:', D17 #Add to left8D2=Collections.deque ()9D2.extendleft (xrange (6)) #从左边加入元素Ten Print 'Extendleft:', D2 OneD2.appendleft (6) #从左边加入元素 A Print 'Appendleft:', D2
D1.append ('H') #只会认为是一个元素加入
D1.extend ('abcdefg') #可以列表元素
Execution result diagram:
The pop and Popleft methods corresponding to the Append and Appendleft methods are used to remove elements from the collection, as shown in the following example:
1 Print " from the right" 2D1=collections.deque ('ABCDEFG')3 Print 'd1==', D14 whileTrue:5 Try: 6 PrintD1.pop (),7 exceptIndexerror:8 Break 9 Print Ten Print '\ n from the left' OneD2=collections.deque (xrange (6)) A Print 'd2==', D2 - whileTrue: - Try: the Printd2.popleft (), - exceptIndexerror: - Break - Print
Execution Result:
Finally, it is worth mentioning that deque is thread-safe, meaning that you can operate from the left and right side of the Deque collection at the same time without affecting it, see the following code:
ImportCollectionsImportThreadingImportTime Candle=collections.deque (Xrange (5)) defBurn (direction,nextsource): whileTrue:Try: Next=Nextsource ()exceptIndexerror: Break Else: Print '%s:%s'%(Direction,next) time.sleep (0.1) Print "Done %s"%directionreturn Left=threading. Thread (target=burn,args= (' Left', Candle.popleft)) Right=threading. Thread (target=burn,args= (' Right', Candle.pop)) Left.start () Right.start () Left.join () Right.join ( )
Collection Series Usage