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

How to use multiple keys when sorting?

There’s this list that I want to sort:

table = [("A", 5, 3), ("B", 5, 6), ("C", 3, 1)]

Inside each tuple, let’s call the elements name, points, ex, in that order.

I want to sort that list by descending order of points, that’s simple enough.

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

But if points are the same for 2 tuples, I’ll sort those by ascending order of ex.

How can I go about doing this?

>Solution :

You can use the "sorted" built-in function with custom ordering function. If you want to make values to be ordered descendently, it’s sufficient to use negatives of the same values.

sorted(table, key = lambda x: (-x[1], x[2]))

Output:

[('A', 5, 3), ('B', 5, 6), ('C', 3, 1)]
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