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

Sort an enumerated list in Python

Actually, my point here is to mark every element of an array before sorting (I’m using enumerate) like this:

arr = [102, 4325, 5125, 657, 2643]
arr = list(enumerate(arr)) # [(0, 102), (1, 4325), (2, 5125), (3, 657), (4, 2643)]

After sort, what I want is that the marks still follow the elements, like:

[(0, 102), (3, 657), (4, 2643), (1, 4325), (2, 5125)]

I need a sort function, or, some kind of mark that can do this. Any help is greatly appreciated. Thank you in advance

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

>Solution :

You can achieve this by using the key argument in the sorted() function. The key argument allows you to specify a function that will be called on each element of the iterable, and the result of that function will be used as the sort key instead of the element itself.

In your case, you want to use the second element of each tuple (i.e., the number in the original list) as the sort key, so you can define a lambda function that extracts that element, like this:

arr = [102, 4325, 5125, 657, 2643]
arr_with_index = list(enumerate(arr)) # [(0, 102), (1, 4325), (2, 5125), (3, 657), (4, 2643)]

sorted_arr_with_index = sorted(arr_with_index, key=lambda x: x[1])

print(sorted_arr_with_index)

This will sort the list based on the second element of each tuple (i.e., the number in the original list), and the first element of each tuple (i.e., the index) will still be associated with its corresponding number after sorting.

Output

# Output: [(0, 102), (3, 657), (4, 2643), (1, 4325), (2, 5125)]
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