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

2024/10/12 18:22:29

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]]
Answer

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).

https://en.xdnf.cn/q/69624.html

Related Q&A

How strings are stored in python memory model

I am from c background and a beginner in python. I want to know how strings are actually stored in memory in case of python.I did something likes="foo"id(s)=140542718184424id(s[0])= 140542719…

The _imaging C module is not installed (on windows)

Im trying to generate some pdf with django/PIL/Imaging and everything is good until I attempt to put some images into the pdf:Exception Type: ImportError Exception Value: The _imaging C module is n…

HOW TO use fabric use with dtach,screen,is there some example

i have googled a lot,and in fabric faq also said use screen dtach with it ,but didnt find how to implement it? bellow is my wrong code,the sh will not execute as excepted it is a nohup taskdef dispatc…

Developing for the HDMI port on Linux

How would it be possible to exclusively drive the HDMI output from an application, without allowing the OS to automatically configure it for display output?For example, using the standard DVI/VGA as t…

Hive client for Python 3.x

is it possible to connect to hadoop and run hive queries using Python 3.x? I am using Python 3.4.1.I found out that it can be done as written here: https://cwiki.apache.org/confluence/display/Hive/Hiv…

How to add a function call to a list?

I have a Python code that uses the following functions:def func1(arguments a, b, c):def func2(arguments d, e, f):def func3(arguments g, h, i):Each of the above functions configures a CLI command on a p…

How to do fuzzy string search without a heavy database?

I have a mapping of catalog numbers to product names:35 cozy comforter 35 warm blanket 67 pillowand need a search that would find misspelled, mixed names like "warm cmfrter".We have code u…

Logging while nbconvert execute

I have a Jupyter notebook that needs to run from the command line. For this I have the following command:jupyter nbconvert --execute my_jupyter_notebook.ipynb --to pythonThis command creates a python s…

How to provide input for a TensorFlow DNNRegressor in Java?

I managed to write a TensorFlow python program with a DNNRegressor. I have trained the model and is able to get a prediction from the model in Python by manually created input (constant tensors). I hav…

Adding breakpoint command lists in GDB controlled from Python script

Im using Python to control GDB via batch commands. Heres how Im calling GDB:$ gdb --batch --command=cmd.gdb myprogramThe cmd.gdb listing just contains the line calling the Python scriptsource cmd.pyAnd…