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 sort an already sorted array by a second property?

Lets say I have a list of tuples, and by calling sort where key = first element, our list comes back as:

[(1, 'e'), (2, 'd'), (3, 'c'), (3, 'a'), (3, 'b'), (4, 'f')]

Now, how do I apply a sort that applies only to those values where the first values match, (in this case, the three values that have first element as 3), so that the final list is:

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

[(1, 'e'), (2, 'd'), (3, 'a'), (3, 'b'), (3, 'c'), (4, 'f')]

I have applied a sort to the first element, but when I apply a sort to the second element, the first sort becomes undone. I would like to keep the original sort, and change ONLY those elements with duplicate first elements.

Thank you!

>Solution :

The default .sort() method in Python already does this. For example, the code:

L = [(1, 'e'), (2, 'd'), (3, 'c'), (3, 'a'), (3, 'b'), (4, 'f')]
L.sort()

print(L)

Returns [(1, 'e'), (2, 'd'), (3, 'a'), (3, 'b'), (3, 'c'), (4, 'f')] which is what you want

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