1

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

klg
  • 85
  • 7

2 Answers2

2

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)]
0

The built-in sorted function takes a key argument you can use to specify a key selector function:

arr = sorted(arr, key=lambda item: item[1])
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206