Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting multiple lists in python based on sorting of a single list

I am a python newbie here, and I have been struck on a rather simple problem - and I am looking for the most efficient way to solve this. So, I have 5 lists as follows:

a,b,c,d,score

where the above lists all have the same size (500 in my case). a,b,c,d are string lists and score is an int list.

What I would like to do is sort a,b,c,d based on ascending or descending sorting of score. So, I would first want to sort score based on a descending pattern, and then sort the corresponding elements in a,b,c,d based on the sorted score list (in the same order).

I was thinking of enumerate to achieve this, but I am wondering if itertools could be used here to make it faster and more efficient.

Any guidance on how this can be achieved would be much appreciated && sorry if this is a 101 question.

like image 834
AJW Avatar asked Sep 14 '25 07:09

AJW


1 Answers

sorted_lists = sorted(izip(a, b, c, d, score), reverse=True, key=lambda x: x[4])
a, b, c, d, score = [[x[i] for x in sorted_lists] for i in range(5)]

In this first step, zip the lists together. This takes the first element from every list and puts them into a tuple, appends that tuple to a new list, then does the same for the second element in every list, and so on. Then we sort this list of tuples by the fifth element (this is from the anonymous function passed into the key argument). We set reverse=True so that the list is descending.

In the second step, we split the lists out using some nested list comprehensions and tuple unpacking. We make a new list of lists, where each inner list is all the first elements of each tuple in sorted_lists. You could do this in one line as below, but I think splitting it into two pieces may be a bit clearer:

a, b, c, d, score = izip(*sorted(izip(a, b, c, d, score), reverse=True,
                         key=lambda x: x[4]))

Here is a generic function that returns a list of tuples, where the tuples are the sorted lists:

def sort_lists_by(lists, key_list=0, desc=False):
    return izip(*sorted(izip(*lists), reverse=desc,
                 key=lambda x: x[key_list]))
like image 162
EML Avatar answered Sep 16 '25 22:09

EML