python collections 模塊 之 deque


class collections.deque(iterable[,maxlen]):

返回 由可迭代對象初始化的 從左向右的 deque 對象。

maxlen: deque 的最大長度,一旦長度超出,會在 相反方向 刪除等量的 items。

append(x): 從 deque 的右邊添加

appendleft(x): 從 deque 的左邊添加

clear(): 移除 deque 中的所有元素

copy(): 淺拷貝 deque

count(x): 計算 deque 中 x 的數量

extend(x): 從右邊擴展 deque

extendleft(x): 從左邊擴展 deque

index(x[,start[,stop]]): 返回 出現在deque 中的第一個 x 的位置,可設置索引的起始和結束

insert(x, i): 在 i 位置 插入 x

pop(): 從deque的右邊刪除

popleft():從deque的左邊刪除

remove(value): 移除 deque 中的 value

reverse(): 翻轉deque

rotate(n=1): 翻轉 deque n 步,右邊至左邊,如果n為負數,則,左邊至右邊

 

 

deque 的應用:

roundrobin:
def roundrobin(*iterables):
    # "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    iterators = deque(map(iter, iterables)) # 生成迭代器
    while iterators:
        try:
            while True:
                yield next(iterators[0]) # 取出最左邊的迭代器的第一個元素
                iterators.rotate(-1) # 將迭代器置於最右
        except StopIteration:
            # Remove an exhausted iterator.
            iterators.popleft() # 如果迭代器為空,則刪除該迭代器

 

保存有限的歷史記錄:
from collections import deque

def search(lines, pattern, history=5):
    previous_lines = deque(maxlen=history)
    for line in lines:
        if pattern in lines:
            yield line, previous_lines
        previous_lines.append(line)


if __name__ == '__main__':
    with open('somefile.txt') as f:
        for line, prevlines in search(f, 'python', 5):
            for pline in prevlines:
                prtin(pline, end='')
            print(line, end='')
            print('-'*20)

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM