python two-way queue deque

Article Directory

1. Two-way queue deque

The double-ended queue can quickly add and push objects from the other side. The deque is a doubly linked list, which is optimized for the insertion and deletion of the continuous data structure of the list .

It provides sequences that can be operated on both ends, which means that you can perform addition or deletion operations on both ends of the sequence. A two-way queue (deque) object supports the following methods :

1. append(): Add element x to the right end of the queue

###定义deque(字符串形式)
d = deque('ghi')  
##或者列表形式定义deque:
# d = deque(['g', 'h', 'i'])
d.append('j') 
d
deque(['g', 'h', 'i', 'j'])

2. appendleft(): Add element x to the left end of the queue

d.appendleft('f')
d
deque(['f', 'g', 'h', 'i', 'j'])

3. clear(): Remove all elements to make their length 0

d = deque('ghi')
d.clear()
d
deque([])

4. copy(): Create a shallow copy

d = deque('xiaoweuge')
y = d.copy()
print(y)
deque(['x', 'i', 'a', 'o', 'w', 'e', 'u', 'g', 'e'])

5. count(): Calculate the number of elements in the deque equal to x

d = deque('xiaoweuge-shuai')
d.count('a')
2

6. extend(): Extend the right side of the deque by adding the elements in the iterable parameter

a = deque('abc')
b = deque('cd')
a.extend(b)
a
deque(['a', 'b', 'c', 'c', 'd'])

#与append 的区别
a = deque('abc')
b = deque('cd')
a.append(b)
deque(['a', 'b', 'c', deque(['c', 'd'])])

7. extendleft(): Extend the left side of the deque by adding the elements in the iterable parameter. Note that when adding to the left, the order in the iterable parameter will be added in reverse in the result

a = deque('abc')
b = deque('cd')
a.extendleft(b)
a
deque(['d', 'c', 'a', 'b', 'c'])

8. index(): Returns the position of element x in deque (after index start, before index stop). Returns the first match, raising ValueError if not found

d = deque('xiaoweuge')
d.index('w')
4

9. insert(): Insert x at position i, if the insertion would cause a deque with a limited length exceeding the length maxlen, an IndexError will be raised

a = deque('abc')
a.insert(1,'X')
deque(['a', 'X', 'b', 'c'])

10. pop(): Remove and return the rightmost element of the deque. Raises an IndexError if there is no element

d = deque('abcj')
d.pop()      
'j'

11. popleft(): Remove and return an element, the leftmost element of the deque. Raises IndexError if there is no element

d = deque('abcj')
d.popleft()
'a'

12. remove(value): Remove the first value found. Raise ValueError if not

a = deque('abca')
a.remove('a')
a
deque(['b', 'c', 'a'])

13. reverse(): Arrange the deque in reverse order and return None

#逆序排列
d = deque('ghi') # 创建一个deque
list(reversed(d))
['i', 'h', 'g']

deque(reversed(d))
deque(['i', 'h', 'g'])

14. rotate(n=1): Circularly move n steps to the right. If n is negative, loop left. If the deque is not empty, one step to the right is equivalent to d.appendleft(d.pop()), and one step to the left is equivalent to d.append(d.popleft())

# 向右边挤一挤
d = deque('ghijkl')
d.rotate(1)                      
d
deque(['l', 'g', 'h', 'i', 'j', 'k'])

# 向左边挤一挤
d.rotate(-1)                     
d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

#看一个更明显的
x = deque('12345')
x
deque(['1', '2', '3', '4', '5'])
x.rotate()
x
deque(['5', '1', '2', '3', '4'])

d = deque(['12','av','cd'])
d.rotate(1)
deque(['cd', '12', 'av']

15. maxlen: the maximum size of Deque, if there is no limit, it will be None

from collections import deque
d=deque(maxlen=10)
for i in range(20):
   d.append(i)
d  
deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

16. Other operations

In addition to the above operations, deque also supports iteration, storage, len(d), reversed(d), copy.deepcopy(d), copy.copy(d), member detection operator in, and subscript references such as through d[0] Access the first element, etc. Indexed access is O(1) at both ends but drops to O(n) in the middle. For fast random access, use a list instead.

Deque supports __add (), mul__(), and __imul__() operations since version 3.5 .

from collections import deque
d = deque('ghi')                 # 创建一个deque

for elem in d:
    print(elem.upper())
G
H
I

#从右边添加一个元素
d.append('j')
d   
deque(['g', 'h', 'i', 'j'])

#从左边添加一个元素
d.appendleft('f')
d 
deque(['f', 'g', 'h', 'i', 'j'])


#右边删除
d.pop()                          
'j'
#左边边删除
d.popleft()
'f'
#看看还剩下啥
list(d)                          # 
['g', 'h', 'i']
#成员检测
'h' in d                         
True
#添加多个元素
d.extend('jkl')              
d
deque(['g', 'h', 'i', 'j', 'k', 'l'])


d.clear()                        # empty the deque
d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):
    File "<pyshell#6>", line 1, in -toplevel-
        d.pop()
IndexError: pop from an empty deque


d.extendleft('abc')              # extendleft() reverses the input order
d
deque(['c', 'b', 'a']

2. Reference link

  1. [Explanation of 10,000-word long text] Python library collections, let you beat 99% of Pythoner

おすすめ

転載: blog.csdn.net/flyingluohaipeng/article/details/129761603