The Deque module is an entry in the Python standard library collections. It provides a sequence that can be manipulated at both ends, which means that you can add or remove both before and after the sequence.
ImportCollections D=collections.deque ('ABCDEFG') Print 'Deque:', DPrint 'Length:', Len (d)Print 'Left end:', D[0]Print 'Right end:', d[-1] D.remove ('C') Print 'Remove (c):'D
Here is the result of the output, as if the result looks like the normal list does not have much difference:
- Deque:deque ([' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G '])
- Length:7
- Left End:a
- Right End:g
- Remove (c): Deque ([' A ', ' B ', ' d ', ' e ', ' f ', ' G '])
However, as can be seen in the following example, Deque is initialized with the Extend method, and you can add the binding element from "left" to the collection by Extendleft:
ImportCollections D1=Collections.deque () d1.extend ('ABCDEFG') Print 'Extend:', D1 d1.append ('h') Print 'Append:', D1#Add to leftD2=Collections.deque () d2.extendleft (xrange (6)) Print 'Extendleft:', D2 D2.appendleft (6) Print 'Appendleft:', D2
From the output results, we can see that append adds the array element from the right side of the collection by default, while the other appendleft can add elements from the left side of the collection, and the output is as follows:
- Extend:deque ([' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G '])
- Append:deque ([' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h '])
- Extendleft:deque ([5, 4, 3, 2, 1, 0])
- Appendleft:deque ([6, 5, 4, 3, 2, 1, 0])
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:
ImportCollectionsPrint " from the right"D=collections.deque ('ABCDEFG') whileTrue:Try: PrintD.pop (),exceptIndexerror: Break Print Print '\ n from the left'D=collections.deque (xrange (6)) whileTrue:Try: Printd.popleft (),exceptIndexerror: Break Print
The output is:
- From the right
- G F E D c B A
- From the left
- 0 1 2 3 4 5
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 ( )
To test thread safety, we have two threads starting from the left and right of deque to move out of the collection element, with the following output:
- left:0
- Right:4
- Right:3left:1
- Left:2
- Done Right
- Done left
Python Deque Module