Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting Nested list in python

I am doing a problem that my school has assigned to me.
Here is code till now:

profits = [1,2,5,6]
weights = [2,3,4,5]
n = 8
ratio = []
count = 0
for i in range(len(profits)):
    ratio.append([])
for i in range(len(ratio)):
    ratio[i].append(weights[i])
    ratio[i].append(profits[i] / weights[i])

The output (ratio):

[[2, 0.5], [3, 0.6666666666666666], [4, 1.25], [5, 1.2]]

But the problem is that I want the list to be sorted maximum ratio wise
like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[4, 1.25], [5, 1.2], [3, 0.6666666666666666], [2, 0.5]]

>Solution :

You can pass a key parameter to .sort().

Below your current code, add:

ratio.sort(key=lambda x: x[1])

to sort on the ratio (as opposed to the default sorting mechanism, which starts at the first element in the list).

After this sorting operation, ratio will be:

[[2, 0.5], [3, 0.6666666666666666], [5, 1.2], [4, 1.25]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading