3

I have a list of objects and I'd like to sort them based on a parallel array. So, as I operate over a list of data I construct a parallel array (where each entry in that list corresponds to an entry in the original list). Then (let's say the parallel array is filled with numbers)

list_a = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9 )
list_b = (4, 2, 5, 6, 1, 7, 3, 9, 0, 8 )

I want to sort the original list of objects based on the parallel arrays values so that the original list is sorting in ascending order by the numerical value in the other array. Is there any way to do this built into python?

sort_a_by_b(list_a, list_b)

Expected result would be:

list_a_sorted_by_b = (8, 4, 1, 6, 0, 2, 3, 5, 9, 7 )
akira
  • 6,050
  • 29
  • 37
avorum
  • 2,243
  • 10
  • 39
  • 49

2 Answers2

6
>>> list_a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list_b = [4, 2, 5, 6, 1, 7, 3, 9, 0, 8]
>>> 
>>> import operator
>>>
>>> [k for k, v in sorted(zip(list_a, list_b), key=operator.itemgetter(1))]
[8, 4, 1, 6, 0, 2, 3, 5, 9, 7]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Call the object list objects and the other list sort_keys. If you can compute sort_keys[i] from just the value of objects[i], you don't even need to build sort_keys. You should just do this:

objects.sort(key=compute_sort_key_for_object)

where compute_sort_key_for_object is the function you would use to compute sort_keys[i] from objects[i]. It's faster and more readable.

If the processing to compute sort_keys is more complex, you'll want Rohit's answer:

import operator
[k for k, v in sorted(zip(objects, sort_keys), key=operator.itemgetter(1))]
user2357112
  • 260,549
  • 28
  • 431
  • 505