Python Deque

python deque

雙端隊列(deque)具有從任一端添加和刪除元素的功能。deque模塊是集合庫的一部分。它具有添加和刪除可以直接用參數(shù)調(diào)用的元素的方法。在下面的程序中,我們導入集合模塊并聲明一個雙端隊列。不需要任何類,我們直接使用內(nèi)置的實現(xiàn)這些方法。

import collections
# create a deque
doubleended = collections.deque(["mon","tue","wed"])
print (doubleended)

# append to the right
print("adding to the right: ")
doubleended.append("thu")
print (doubleended)

# append to the left
print("adding to the left: ")
doubleended.appendleft("sun")
print (doubleended)

# remove from the right
print("removing from the right: ")
doubleended.pop()
print (doubleended)

# remove from the left
print("removing from the left: ")
doubleended.popleft()
print (doubleended)

# reverse the dequeue
print("reversing the deque: ")
doubleended.reverse()
print (doubleended)

當上面的代碼被執(zhí)行時,它會產(chǎn)生以下結(jié)果:

deque(['mon', 'tue', 'wed'])
adding to the right:
deque(['mon', 'tue', 'wed', 'thu'])
adding to the left:
deque(['sun', 'mon', 'tue', 'wed', 'thu'])
removing from the right:
deque(['sun', 'mon', 'tue', 'wed'])
removing from the left:
deque(['mon', 'tue', 'wed'])
reversing the deque:
deque(['wed', 'tue', 'mon'])

下一節(jié):python 高級鏈表

python 數(shù)據(jù)結(jié)構(gòu)

相關(guān)文章
亚洲国产精品第一区二区,久久免费视频77,99V久久综合狠狠综合久久,国产免费久久九九免费视频