gpt4 book ai didi

Python heapq : How do I sort the heap using nth element of the list of lists?

转载 作者:太空宇宙 更新时间:2023-11-04 09:55:51 27 4
gpt4 key购买 nike

所以我有列表列表被添加到堆中;例如:

 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) 推送和弹出:

 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 并为该列表实现比较函数:

class MyList(list):
def __lt__(self, other):
return self[2] < other[2]

q = [MyList(x) for x in n]

注意:您应该实现其他比较函数(请参阅 functools.total_ordering 了解如何轻松实现)。

关于Python heapq : How do I sort the heap using nth element of the list of lists?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com