# 使用优先级队列-heapq

代码：

```python
import heapq


class PriorityQueue:
    def __init__(self):
        # 队列数据存放变量
        self._queue=[]
        # 事例化对象索引值，以便用于排序
        self._index=0

    def push(self,item,priority):
        # 往（优先）队列中加数据
        # 以元组为判断依据，（优先级变量priority为负，实现优先级高到低优先级排序），
        # 元组第一个相同时，才会比较第二位（self._index）的值，其自增长，以保证顺序和加入顺序相同；第3为才是真正的数据
        heapq.heappush(self._queue,(-priority,self._index,item))
        self._index+=1

    def pop(self):
        # 取弹出数据元组的最后一位(-priority,self._index,item)，item位对象的数据
        #return heapq.heappop(self._queue)[2]
        return heapq.heappop(self._queue)[-1]


class Item:
    def __init__(self,name):
        self.name=name

    def __repr__(self):
        # 以便于自动被print打印
        return 'Item:{}'.format(self.name)
q=PriorityQueue()
q.push(Item('AAA'),1)
q.push(Item('BBB'),9)
q.push(Item('CCC'),5)
q.push(Item('DDD'),3)
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
```

结果：

```python
Item:BBB
Item:CCC
Item:DDD
Item:AAA
```

视频：

```
wait
```

附 heapq堆数据结构使用

代码：

```python
import heapq
'''
堆是二叉树，最大堆中父节点大于或等于两个子节点，最小堆父节点小于或等于两个子节点。
'''
print('创建，获取最小值。heap[0]','-'*50)
nums = [2, 3, 5, 1, 54, 23, 132]
heap = []
print('nums',nums)
for num in nums:
    heapq.heappush(heap, num)  # 加入堆
print('heap[0]:',heap[0])  # 只获取最小值，不是弹出
print()



print('创建，转换列表成为堆结构。heapq.heapify(nums)','-'*50)
print(nums)
nums = [2, 3, 5, 1, 54, 23, 132]
heapq.heapify(nums)#转成堆结构，nums改变
print(nums)
print([heapq.heappop(nums) for _ in range(len(nums))])#转成堆结构才能按顺序打印
print()



print('合并多个排序序列成一个排序序列，返回值的迭代器。nums=heapq.merge(nums1,nums2)')
nums1 = [2, 3, 5, 1, 54, 23, 132]
nums1=sorted(nums1)
print('nums1',nums1)
nums2 = [22, 23, 25, 21, 254, 223, 2132]
nums2=sorted(nums2)
print('nums2',nums2)
nums=heapq.merge(nums1,nums2) #值的迭代器
print('nums',list(nums))
print()


print('删除堆中最小元素并加入一个元素23。heapq.heaprepalce()')
nums = [1, 2, 4, 5, 3]
print('nums',nums)
heapq.heapreplace(nums, 23)
print([heapq.heappop(nums) for _ in range(len(nums))])
print()


print('最大/小的k个值。heapq.nlargest(3, nums)/heapq.nsmallest(3, nums)')
nums = [1, 3, 4, 5, 2,9]
print(nums)
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
```

结果：

```python
创建，获取最小值。heap[0] --------------------------------------------------
nums [2, 3, 5, 1, 54, 23, 132]
heap[0]: 1

创建，转换列表成为堆结构。heapq.heapify(nums) --------------------------------------------------
[2, 3, 5, 1, 54, 23, 132]
[1, 2, 5, 3, 54, 23, 132]
[1, 2, 3, 5, 23, 54, 132]

合并多个排序序列成一个排序序列，返回值的迭代器。nums=heapq.merge(nums1,nums2)
nums1 [1, 2, 3, 5, 23, 54, 132]
nums2 [21, 22, 23, 25, 223, 254, 2132]
nums [1, 2, 3, 5, 21, 22, 23, 23, 25, 54, 132, 223, 254, 2132]

删除堆中最小元素并加入一个元素23。heapq.heaprepalce()
nums [1, 2, 4, 5, 3]
[2, 3, 4, 5, 23]

最大/小的k个值。heapq.nlargest(3, nums)/heapq.nsmallest(3, nums)
[1, 3, 4, 5, 2, 9]
[9, 5, 4]
[1, 2, 3]
```

视频：

```
wait
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/python/2.2.7-shi-yong-you-xian-ji-dui-lie.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
