python deque
Python的collections中有一个deque,这个对象类似于list列表,不过你可以操作它的“两端”。比如下面的例子:
- import collections
- d=collections.deque('abcdefg')
- print 'Deque:',d
- print 'Length:',len(d)
- print 'Left end:',d[0]
- print 'Right end:',d[-1]
- d.remove('c')
- print 'remove(c):',d
- 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'])
- import collections
- d1=collections.deque()
- d1.extend('abcdefg')
- print 'extend:',d1
- d1.append('h')
- print 'append:',d1
- # add to left
- d2=collections.deque()
- d2.extendleft(xrange(6))
- print 'extendleft:',d2
- d2.appendleft(6)
- print 'appendleft:',d2
- 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])
- import collections
- print "From the right"
- d=collections.deque('abcdefg')
- while True:
- try:
- print d.pop(),
- except IndexError:
- break
- print '\n From the left'
- d=collections.deque(xrange(6))
- while True:
- try:
- print d.popleft(),
- except IndexError:
- break
- From the right
- g f e d c b a
- From the left
- 0 1 2 3 4 5
- import collections
- import threading
- import time
- candle=collections.deque(xrange(5))
- def burn(direction,nextSource):
- while True:
- try:
- next=nextSource()
- except IndexError:
- break
- else:
- print '%s : %s' % (direction,next)
- time.sleep(0.1)
- print "done %s" % direction
- return
- 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()
- left : 0
- right : 4
- right : 3left : 1
- left : 2
- done right
- done left