Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sorting based on parallel arrays [duplicate]

Tags:

python

sorting

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 )
like image 569
avorum Avatar asked Jul 23 '26 14:07

avorum


2 Answers

>>> 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]
like image 91
Rohit Jain Avatar answered Jul 26 '26 04:07

Rohit Jain


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))]
like image 31
user2357112 supports Monica Avatar answered Jul 26 '26 03:07

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!