ใน Python deque เป็นโครงสร้างข้อมูลคล้าย stack และ queue มันอนุญาตให้ทำการ append และ pop จากทั้งสองปลายของคิว และนั่นทำให้มันแตกต่างจากโครงสร้างข้อมูลอื่นๆ มีการดำเนินการต่างๆ ด้านล่างที่ใช้กับ deque ในบทความนี้เราจะมาดูตัวอย่างในแต่ละการดำเนินการ โมดูล collections ถูกใช้เพื่อนำ deque ไปใช้
การดำเนินการของ Deque
ด้านล่างเป็นการดำเนินการที่มีประโยชน์บางอย่างที่ทำได้ด้วย deque
append() − ฟังก์ชันนี้ใช้เพื่อแทรกค่าในอาร์กิวเมนต์ไปที่ปลายขวาของ deque
appendleft() − ฟังก์ชันนี้ใช้เพื่อแทรกค่าในอาร์กิวเมนต์ไปที่ปลายซ้ายของ deque
pop() − ฟังก์ชันนี้ใช้เพื่อลบอาร์กิวเมนต์จากปลายขวาของ deque
popleft() − ฟังก์ชันนี้ใช้เพื่อลบอาร์กิวเมนต์จากปลายซ้ายของ deque
extend(iterable) − ฟังก์ชันนี้ใช้เพื่อเพิ่มหลายค่าที่ปลายขวาของ deque อาร์กิวเมนต์ที่ส่งคือ iterable
extendleft(iterable) − ฟังก์ชันนี้ใช้เพื่อเพิ่มหลายค่าที่ปลายซ้ายของ deque อาร์กิวเมนต์ที่ส่งคือ iterable ลำดับจะถูกกลับเนื่องจากการ append ด้านซ้าย
reverse() − ฟังก์ชันนี้ใช้เพื่อกลับลำดับขององค์ประกอบ deque
rotate() − ฟังก์ชันนี้หมุน deque ตามจำนวนที่ระบุในอาร์กิวเมนต์ หากจำนวนที่ระบุเป็นลบ การหมุนจะเกิดขึ้นทางซ้าย มิฉะนั้นจะหมุนทางขวา
ตัวอย่าง
โปรแกรมด้านล่างแสดงวิธีนำการดำเนินการข้างต้นไปใช้กับ deque และโมดูล collections
import collections
de = collections.deque([10, 20, 30, 40])
print(de)
de.append(50)
print("\nAppending at right the deque is : ")
print(de)
de.appendleft(60)
print("\nAppending at left the deque is : ")
print(de)
de.pop()
print("\nDeleting from right the deque is: ")
print(de)
de.popleft()
print("\nDeleting from left the deque is: ")
print(de)
de.extend([70, 80])
print("\nExtending deque at end is : ")
print(de)
de.extendleft([100, 90])
print("\nExtending deque at beginning is : ")
print(de)
de.rotate(-2)
print("\nRotating deque is : ")
print(de)
de.reverse()
print("\nReversing deque is : ")
print(de)
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลดังนี้ −
deque([10, 20, 30, 40]) Appending at right the deque is : deque([10, 20, 30, 40, 50]) Appending at left the deque is : deque([60, 10, 20, 30, 40, 50]) Deleting from right the deque is: deque([60, 10, 20, 30, 40]) Deleting from left the deque is: deque([10, 20, 30, 40]) Extending deque at end is : deque([10, 20, 30, 40, 70, 80]) Extending deque at beginning is : deque([90, 100, 10, 20, 30, 40, 70, 80]) Rotating deque is : deque([10, 20, 30, 40, 70, 80, 90, 100]) Reversing deque is : deque([100, 90, 80, 70, 40, 30, 20, 10])