Python的deque適用於需要高效處理兩端操作的場景。 1. 創(chuàng)建時可傳入列表或字符串,也可初始化為空再添加元素;2. 使用append()和appendleft()分別在右端和左端添加元素;3. 使用pop()和popleft()分別從右端和左端移除元素;4. rotate(n)方法將元素向右(正數(shù))或向左(負數(shù))循環(huán)移動;5. 設置maxlen參數(shù)後,超出容量時會自動丟棄對端舊元素;6. 適合用於隊列、滑動窗口、歷史記錄等場景。相比列表,deque在首部操作具有O(1)時間複雜度,性能更優(yōu)。
The deque
(double-ended queue) from Python's collections
module is a versatile and efficient data structure, especially when you need fast appends and pops from both ends. If you're used to working with lists, switching to deque
can give you performance boosts in certain situations.
Let's break down how to use it effectively.
Creating and Initializing a Deque
To start using deque
, you first need to import it from the collections
module. Then you can create one by passing in an iterable like a list or string.
from collections import deque d = deque([1, 2, 3])
You can also initialize it empty and add elements later. It's pretty flexible — strings, tuples, and even other deques work as input.
If you're starting from scratch:
- Use
append()
to add to the right end - Use
appendleft()
to add to the left end
d = deque() d.append(1) # deque([1]) d.appendleft(0) # deque([0, 1])
Adding and Removing Elements Efficiently
One of the main advantages of deque
over regular lists is its speed for operations at both ends. With a normal list, inserting or removing from the front ( pop(0)
or insert(0, x)
) takes O(n) time, which gets slow for large data sets. deque
does these operations in O(1) time.
Here are some common operations:
- Add to the right :
append(x)
- Add to the left :
appendleft(x)
- Remove from the right :
pop()
- Remove from the left :
popleft()
d = deque([1, 2, 3]) d.append(4) # deque([1, 2, 3, 4]) d.popleft() # returns 1 → deque([2, 3, 4])
This makes deque
perfect for things like queues or sliding window problems.
Rotating and Managing Elements
Another handy feature is the rotate()
method. It shifts elements in place to the right (or left if given a negative number).
For example:
d = deque([1, 2, 3, 4, 5]) d.rotate(1) # deque([5, 1, 2, 3, 4])
That moves each element one position to the right, wrapping around the end. A negative rotation goes the other way:
d.rotate(-1) # back to deque([1, 2, 3, 4, 5])
Also, if you ever need to limit the size of your deque, you can set the maxlen
parameter when creating it. Once full, adding new items will automatically drop the oldest ones from the opposite end.
d = deque(maxlen=3) d.append(1) d.append(2) d.append(3) d.append(4) # now contains [2, 3, 4]
This is super useful for tracking recent values or implementing fixed-size buffers.
When to Use Deque Instead of List
In most cases, you'll still want to use a regular list. But if you find yourself frequently doing:
- Insertions/removals at the beginning
- Implementing queues or stacks
- Maintaining a history or buffer of recent items
Then deque
is the better choice.
Even though they look similar and support many of the same methods, their performance characteristics differ. So if you're building something that needs high efficiency on both ends, switch to deque
.
基本上就這些。掌握幾個常用方法之後,你會發(fā)現(xiàn)它在很多場景下比列表更合適,而且用起來也不復雜。
以上是如何使用Python中的集合模塊中的Deque數(shù)據(jù)結(jié)構(gòu)?的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動的應用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍?,指“一種接口,多種實現(xiàn)”,允許統(tǒng)一處理不同類型的對象。 1.多態(tài)通過方法重寫實現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實現(xiàn)。 2.多態(tài)的實際用途包括簡化代碼結(jié)構(gòu)、增強可擴展性,例如圖形繪製程序中統(tǒng)一調(diào)用draw()方法,或遊戲開發(fā)中處理不同角色的共同行為。 3.Python實現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實現(xiàn)相同方法即可,這稱為“鴨子類型”。 4.注意事項包括保持方

參數(shù)(parameters)是定義函數(shù)時的佔位符,而傳參(arguments)是調(diào)用時傳入的具體值。 1.位置參數(shù)需按順序傳遞,順序錯誤會導致結(jié)果錯誤;2.關(guān)鍵字參數(shù)通過參數(shù)名指定,可改變順序且提高可讀性;3.默認參數(shù)值在定義時賦值,避免重複代碼,但應避免使用可變對像作為默認值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用於通用接口或裝飾器,但應謹慎使用以保持可讀性。

迭代器是實現(xiàn)__iter__()和__next__()方法的對象,生成器是簡化版的迭代器,通過yield關(guān)鍵字自動實現(xiàn)這些方法。 1.迭代器每次調(diào)用next()返回一個元素,無更多元素時拋出StopIteration異常。 2.生成器通過函數(shù)定義,使用yield按需生成數(shù)據(jù),節(jié)省內(nèi)存且支持無限序列。 3.處理已有集合時用迭代器,動態(tài)生成大數(shù)據(jù)或需惰性求值時用生成器,如讀取大文件時逐行加載。注意:列表等可迭代對像不是迭代器,迭代器到盡頭後需重新創(chuàng)建,生成器只能遍歷一次。

類方法是Python中通過@classmethod裝飾器定義的方法,其第一個參數(shù)為類本身(cls),用於訪問或修改類狀態(tài)。它可通過類或?qū)嵗{(diào)用,影響的是整個類而非特定實例;例如在Person類中,show_count()方法統(tǒng)計創(chuàng)建的對像數(shù)量;定義類方法時需使用@classmethod裝飾器並將首參命名為cls,如change_var(new_value)方法可修改類變量;類方法與實例方法(self參數(shù))、靜態(tài)方法(無自動參數(shù))不同,適用於工廠方法、替代構(gòu)造函數(shù)及管理類變量等場景;常見用途包括從

處理API認證的關(guān)鍵在於理解並正確使用認證方式。 1.APIKey是最簡單的認證方式,通常放在請求頭或URL參數(shù)中;2.BasicAuth使用用戶名和密碼進行Base64編碼傳輸,適合內(nèi)部系統(tǒng);3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應對Token過期,可封裝Token管理類自動刷新Token;總之,根據(jù)文檔選擇合適方式,並安全存儲密鑰信息是關(guān)鍵。

Python的magicmethods(或稱dunder方法)是用於定義對象行為的特殊方法,它們以雙下劃線開頭和結(jié)尾。 1.它們使對象能夠響應內(nèi)置操作,如加法、比較、字符串表示等;2.常見用例包括對像初始化與表示(__init__、__repr__、__str__)、算術(shù)運算(__add__、__sub__、__mul__)及比較運算(__eq__、__lt__);3.使用時應確保其行為符合預期,例如__repr__應返回可重構(gòu)對象的表達式,算術(shù)方法應返回新實例;4.應避免過度使用或以令人困惑的方

Pythonmanagesmemoryautomaticallyusingreferencecountingandagarbagecollector.Referencecountingtrackshowmanyvariablesrefertoanobject,andwhenthecountreacheszero,thememoryisfreed.However,itcannothandlecircularreferences,wheretwoobjectsrefertoeachotherbuta

@property是Python中用於將方法偽裝成屬性的裝飾器,允許在訪問屬性時執(zhí)行邏輯判斷或動態(tài)計算值。 1.它通過@property裝飾器定義getter方法,使外部像訪問屬性一樣調(diào)用方法;2.搭配.setter可控制賦值行為,如校驗值合法性,不定義.setter則為只讀屬性;3.適用於屬性賦值校驗、動態(tài)生成屬性值、隱藏內(nèi)部實現(xiàn)細節(jié)等場景;4.使用時注意屬性名與私有變量名不同名,避免死循環(huán),適合輕量級操作;5.示例中Circle類限制radius非負,Person類動態(tài)生成full_name屬
