热线电话:13121318867

登录
2020-11-04 阅读量: 720
Deque在Python中如何实现?

问题详述:Deque在Python中如何实现?


解答:

可以使用模块“ collections ” 在python中实现Deque 。双端队列优于在列表中,我们需要更快从容器的两端追加和弹出操作的情况下,如双端队列提供了一种O(1)相比于列表进行追加和弹出操作时间复杂度,其提供O(n)的时间复杂度。


deque操作:


1. append(): - 此函数用于参数中的值插入 deque 的右端


2. appendleft(): - 此函数用于参数中的值插入 deque 的左端


3. pop(): - 此函数用于从双端队列的右端删除一个参数。


4. popleft(): - 此函数用于从双端队列的左端删除一个参数。


# Python code to demonstrate working of

# append(), appendleft(), pop(), and popleft()


# importing "collections" for deque operations

import collections


# initializing deque

de = collections.deque([1,2,3])


# using append() to insert element at right end

# inserts 4 at the end of deque

de.append(4)


# printing modified deque

print ("The deque after appending at right is : ")

print (de)


# using appendleft() to insert element at right end

# inserts 6 at the beginning of deque

de.appendleft(6)


# printing modified deque

print ("The deque after appending at left is : ")

print (de)


# using pop() to delete element from right end

# deletes 4 from the right end of deque

de.pop()


# printing modified deque

print ("The deque after deleting from right is : ")

print (de)


# using popleft() to delete element from left end

# deletes 6 from the left end of deque

de.popleft()


# printing modified deque

print ("The deque after deleting from left is : ")

print (de)



26.0724
0
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子