所以我有一些列表被添加到堆中;例如:
n = [[1, 5, 93], [2, 6, 44], [4, 7, 45], [6, 3, 12]] heapq.heapify(n) print(n)
这将根据列表的第一个元素进行比较和排序。
我的问题是,如何对 heapq 进行排序,以便它比较每个列表的第三个元素?例如,可以按以下顺序从 heapq 访问上面的列表:
[[6, 3, 12], [2, 6, 44], [4, 7, 45], [1, 5, 93]]
heapq不支持key函数的顺序,因此您将需要操作您的数据结构。将您的列表映射到tuple(sort_value, list)会让你做log(n)推入和弹出:
heapq
key
tuple(sort_value, list)
log(n)
In []: q = [(x[2], x) for x in n] heapq.heapify(q) heapq.heappop(q) Out[]: (12, [6, 3, 12]) In []: l = [2, 5, 1] heapq.heappush(q, (l[2], l)) heapq.heappop(q) Out[]: (1, [2, 5, 1])
或者,定义您自己的list并实现该列表的比较函数:
list
class MyList(list): def __lt__(self, other): return self[2] < other[2] q = [MyList(x) for x in n]
注意:您应该实现其他比较函数(请参阅functools.total_ordering关于如何轻松做到这一点)。
functools.total_ordering