So I have lists of lists getting added to the heap; eg:
n = [[1, 5, 93],
[2, 6, 44],
[4, 7, 45],
[6, 3, 12]]
heapq.heapify(n)
print(n)
This compares and sorts according to the list's first element.
My question is, how do I sort the heapq so it compares the third element of each list? For example, the above list would be accessed from the heapq in this order:
[[6, 3, 12],
[2, 6, 44],
[4, 7, 45],
[1, 5, 93]]
The heapq implements a min-heap sort algorithm suitable for use with Python's lists. A heap is a tree-like data structure where the child nodes have a sort-order relationship with the parents.
The heapq module functions can take either a list of items or a list of tuples as a parameter. Thus, there are two ways to customize the sorting process: Convert the iterable to a list of tuples/list for comparison. Write a wrapper class that overrides '<' operator.
The heapq module of python implements the heap queue algorithm. It uses the min heap where the key of the parent is less than or equal to those of its children.
heapify function does not give sorted list.
heapq
doesn't support a key
function for it's ordering so you will need to manipulate your data structure. Mapping your list to a tuple(sort_value, list)
will allow you to do log(n)
push and pop:
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])
Alternatively, define your own list
and implement the comparison function for that list:
class MyList(list):
def __lt__(self, other):
return self[2] < other[2]
q = [MyList(x) for x in n]
Note: you should implement the other comparison functions (see functools.total_ordering
on how to do that easily).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With