In [1]:
import collections
d = collections.deque('abcdefg')
print('Deque', d)
print('length', len(d))
print('Left end:', d[0])
print('Right end:', d[-1])
In [3]:
d.remove('c')
In [6]:
print('remove(c)', d)
In [7]:
import collections
d1 = collections.deque()
d1.extend('abcdefg')
print('extend', d1)
d1.append('h')
print('append', d1)
In [8]:
d2 = collections.deque()
d2.extendleft(range(6))
print('extend left', d2)
d2.appendleft(6)
print('append left', d2)
In [9]:
import collections
print('From the right')
d = collections.deque('abcdef')
while True:
try:
print(d.pop(), end=' ')
except IndexError:
break
print()
print('\n From the left:')
d = collections.deque(range(6))
while True:
try:
print(d.popleft(), end=' ')
except IndexError:
break
the deque is thread safe
In [10]:
import collections
import threading
import time
candle = collections.deque(range(5))
def burn(direction, nextSource):
while True:
try:
next = nextSource()
except IndexError:
break
else:
print('{:>8}:{}'.format(direction, next))
time.sleep(0.1)
print('{:>8} done'.format(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()
In [11]:
import collections
d = collections.deque(range(10))
print('Normal :', d)
d = collections.deque(range(10))
d.rotate(2)
print('Right rotation :', d)
d = collections.deque(range(10))
d.rotate(-2)
print('Left rotation :', d)
In [12]:
import collections
import random
random.seed(1)
d1 = collections.deque(maxlen=3)
d2 = collections.deque(maxlen=3)
for i in range(4):
n = random.randint(0, 100)
print('n= ', n)
d1.append(n)
d2.appendleft(n)
print('D1:' ,d1)
print('D2:', d2)