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

标签 python

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

 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/

相关文章:

python - 将 Python 文件夹移动到 Program Files 文件夹?

python - 如何更改字典值中字符串中的数字?

Python 线程不想关闭

Python 无法放置模块

python - Pyside2如何获取鼠标位置?

python - MySQLdb 连接到数据库错误

python - CommandOnCooldown 错误处理程序未捕获错误!已经测试了一切

python: IndexError: 元组索引超出范围

Python3 将值附加到数组,但前提是它不是 None

python - 即使严格的输入有效,表单验证上的 Django TestCase 也会失败