简体   繁体   English

Python heapq 优先级队列 Maxheap

[英]Python heapq Priority Queue Maxheap

I understand that priority queues using heapq are implemented as a minheap.我知道使用 heapq 的优先级队列是作为 minheap 实现的。 I need to make a priority queue implemented as a maxheap that sorts elements by an AWS datetime string.我需要将优先级队列实现为 maxheap,它按 AWS 日期时间字符串对元素进行排序。 I want elements with the most recent datetime to be popped off of the queue first when I call the heapq.heappop() method.当我调用 heapq.heappop() 方法时,我希望具有最新日期时间的元素首先从队列中弹出。 Everything online seems to point towards just using the minheap but making your values negative during input so that greater values are pushed to the top instead of the bottom.网上的一切似乎都指向仅使用 minheap,但在输入期间使您的值变为负值,以便将更大的值推到顶部而不是底部。 However, I can't seem to find any way to actually apply this to a datetime string like this '2021-06-03T16:11:14.206650Z'.但是,我似乎找不到任何方法将其实际应用于日期时间字符串,例如“2021-06-03T16:11:14.206650Z”。 Is there a way that I can make that string 'negative' or somehow make it so that more recent dates are popped from the heap first?有没有一种方法可以使该字符串成为“负数”或以某种方式使它成为较新的日期首先从堆中弹出?

There are several ways to approach this.有几种方法可以解决这个问题。

One is to convert the date/time to an ordinal, and negate that一种是将日期/时间转换为序数,然后取反

-dateutil.parser.parse('2021-06-03T16:11:14.206650Z').toordinal()

If you want to retain the original date string, then put this number in a tuple together with the date string.如果要保留原始日期字符串,则将此数字与日期字符串一起放在一个元组中。

Convert your timestamps to offsets from a maximum timestamp.将您的时间戳转换为最大时间戳的偏移量。 Then the most recent timestamps will have the smallest keys, making a minheap appropriate.然后最近的时间戳将具有最小的键,使最小堆合适。

Note that dateutil is a third-party module.请注意, dateutil是第三方模块。

>>> import datetime, dateutil
>>> now = datetime.datetime.now().timestamp()
>>> june3 = dateutil.parser.isoparse('2021-06-03T16:11:14.206650Z').timestamp()
>>> june1 = dateutil.parser.isoparse('2021-06-01T00:00:00Z').timestamp()
>>> now - june3 < now - june1
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM