python deque队列 列表中最大或最小的N个元素

2020-06-23  本文已影响0人  g_ices

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应用

# 队列型列表,可以指定队列长度,头部或者尾部添加元素、删除元素


from collections import deque

# 加参数代表指定长度队列
# 不加参数代表任意长度的队列
q = deque()
q.append(3)
q.append(4)
# 指定索引插入元素
q.insert(1, 30)

# 指定最左侧添加元素
q.appendleft(10)
# 删除队列最后一个元素
q.pop()
# 删除队列第一个元素
q.popleft()
# 删除指定元素
q.remove(30)
# 清除队列所有元素
q.clear()
# 查询指定元素在队列中的个数
num = q.count(3)
print(q)


列表中最大或最小的N个元素

import heapq


nums = [1,8,2,23,7,18,34,53,21]

# 查询指定列表中指定个数的较大元素
print(heapq.nlargest(3, nums))

# 查询指定列表中指定个数的较小元素
print(heapq.nsmallest(3,nums))

# 删除最左侧第一个元素
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)

上一篇 下一篇

猜你喜欢

热点阅读