Python 如何在保留列表的同时,按某个索引从矩阵中堆出列表?

Python 如何在保留列表的同时,按某个索引从矩阵中堆出列表?,python,python-3.x,python-2.7,binary-heap,Python,Python 3.x,Python 2.7,Binary Heap,假设我有一张清单: l1=[[1,3],[3,2],[2,1]] 我想将l1中的每个项推送到一个二进制堆中,“内存”,但在二进制堆中按每个项[-1]排序 我尝试过:heapq.heappush(\u heap,item=itemgetter(-1))和使用匿名函数的等效函数,但我得到: TypeError:heappush()不接受关键字参数一个选项是在heapq函数周围制作小包装,以一致的方式向项中预发送/提取排序值: def heappush(h, item, key=lambda x: x

假设我有一张清单:

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

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

我尝试过:
heapq.heappush(\u heap,item=itemgetter(-1))
和使用匿名函数的等效函数,但我得到:


TypeError:heappush()不接受关键字参数

一个选项是在
heapq
函数周围制作小包装,以一致的方式向项中预发送/提取排序值:

def heappush(h, item, key=lambda x: x):
    heapq.heappush(h, (key(item), item))

def heappop(h):
    return heapq.heappop(h)[1]

def heapify(h, key=lambda x: x):
    for idx, item in enumerate(h):
        h[idx] = (key(item), item)
    heapq.heapify(h)
使用您的样本进行测试:

l1 = [[1, 3], [3, 2], [2, 1]]
h = []
for item in l1:
    heappush(h, item, key=itemgetter(-1))

while h:
    print(heappop(h))
印刷品:

[2, 1]
[3, 2]
[1, 3]

注意,您可以使用
h=l1;heapify(h,key=itemgetter(-1))
应该比单独
heappush
处理每个项目更快。

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


我喜欢Eugene的解决方案,但如果经常使用这个特殊的元组,可以定义一个自定义对象来实现这一点,如下所示:

from heapq import heappush, heappop

class MyTupleHeapObj(object):
    def __init__(self,val): self.val = val
    def __lt__(self,other): return self.val[-1] < other.val[-1]
    def __eq__(self,other): return self.val == other.val
    def __str__(self): return str(self.val)

h = []
for item in [[1, 3], [3, 2], [2, 1]]:
    heappush(h, MyTupleHeapObj(item))

while h:
    print heappop(h)

您应该在输入进入堆时反转它们。它们自然会按照它们的第一个值(初始列表的最后一个值)进行排序。@fferri好极了,谢谢你的提示!
from heapq import heappush, heappop

class MyTupleHeapObj(object):
    def __init__(self,val): self.val = val
    def __lt__(self,other): return self.val[-1] < other.val[-1]
    def __eq__(self,other): return self.val == other.val
    def __str__(self): return str(self.val)

h = []
for item in [[1, 3], [3, 2], [2, 1]]:
    heappush(h, MyTupleHeapObj(item))

while h:
    print heappop(h)
[2, 1]
[3, 2]
[1, 3]