Skip to main content
 首页 » 编程设计

python之如何在保留列表的同时通过某个索引从矩阵中 heappush 列表

2024年09月07日30langtianya

假设我有一个列表:

l1 = [[1, 3], [3, 2], [2, 1]]

我想将 l1 中的每个项目推送到二进制堆,“内存”,但在二进制堆中按 each_item[-1] 排序。

我试过:heapq.heappush(_heap, item=itemgetter(-1)) 和使用匿名函数的等价物,但我得到:

TypeError: heappush() 没有关键字参数

请您参考如下方法:

您可以将堆中的条目存储为 3 元素元组,包括最后一个元素、条目计数和实际项目。这样,项目将按其最后一个值排序,条目计数确保排序稳定性(即,最后一个元素相同的两个项目按添加顺序返回):

>>> import heapq 
>>> heap = [] 
>>> l1 = [[1, 3], [3, 2], [2, 1]] 
>>> for count, item in enumerate(l1): 
...     heapq.heappush(heap, (item[-1], count, item)) 
...  
>>> while heap: 
...     print(heapq.heappop(heap)[-1]) 
...  
[2, 1] 
[3, 2] 
[1, 3]