deque底層
def search(lines, pattern, history = 5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line,previous_lines
previous_lines.append(line)
if __name__ == '__main__':
with open('somefile.txt') as file:
for line, prevlines in search(file, 'python', 2):
for pline in prevlines:
print(pline)
print(line, end=' ')
print('_' *20)
deque應(yīng)用
# 隊(duì)列型列表烦秩,可以指定隊(duì)列長度赃份,頭部或者尾部添加元素矫废、刪除元素
from collections import deque
# 加參數(shù)代表指定長度隊(duì)列
# 不加參數(shù)代表任意長度的隊(duì)列
q = deque()
q.append(3)
q.append(4)
# 指定索引插入元素
q.insert(1, 30)
# 指定最左側(cè)添加元素
q.appendleft(10)
# 刪除隊(duì)列最后一個(gè)元素
q.pop()
# 刪除隊(duì)列第一個(gè)元素
q.popleft()
# 刪除指定元素
q.remove(30)
# 清除隊(duì)列所有元素
q.clear()
# 查詢指定元素在隊(duì)列中的個(gè)數(shù)
num = q.count(3)
print(q)
列表中最大或最小的N個(gè)元素
import heapq
nums = [1,8,2,23,7,18,34,53,21]
# 查詢指定列表中指定個(gè)數(shù)的較大元素
print(heapq.nlargest(3, nums))
# 查詢指定列表中指定個(gè)數(shù)的較小元素
print(heapq.nsmallest(3,nums))
# 刪除最左側(cè)第一個(gè)元素
heapq.heappop(nums)
print(nums)
# 修改列表本身,將列表排序
heapq.heapify(nums)
print(nums)
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 53.1},
{'name': 'C', 'shares': 60, 'price': 254.1},
{'name': 'Java', 'shares': 80, 'price': 21.1},
{'name': 'C++', 'shares': 500, 'price': 1589.1},
{'name': 'python', 'shares': 150, 'price': 45.1},
{'name': 'go', 'shares': 79, 'price': 45.1},
]
# 按照price的值從大到小排序portfolio
cheap = heapq.nsmallest(3, portfolio, key=lambda x:x['price'])
print(cheap)
# 按照price的值從小到大排序portfolio
nlarge = heapq.nlargest(3, portfolio, key=lambda x:x['price'])
print(nlarge)