Python: How to sort a list_of_lists based on another list_of_lists?

Viewed 540

Below is the use-case I am trying to solve:

I have 2 lists of lists: (l and d)

In [1197]: l
Out[1197]: 
[['Cancer A', 'Ecog 9', 'Fill 6'],
 ['Cancer B', 'Ecog 1', 'Fill 1'],
 ['Cancer A', 'Ecog 0', 'Fill 0']]

In [1198]: d
Out[1198]: [[100], [200], [500]]

It's a 2-part problem here:

  1. Sort l based on the priority of values. eg: Cancer, Ecog and Fill (in this case key=(0,1,2)). It could be anything like Ecog, Cancer, Fill so, key=(1,0,2).
  2. Sort d in the same order in which l has been sorted int above step.

Step #1 I'm able to achieve, like below:

In [1199]: import operator
In [1200]: sorted_l = sorted(l, key=operator.itemgetter(0,1,2))

In [1201]: sorted_l
Out[1200]: 
[['Cancer A', 'Ecog 0', 'Fill 0'],
 ['Cancer A', 'Ecog 9', 'Fill 6'],
 ['Cancer B', 'Ecog 1', 'Fill 1']]

Now, I want to sort values of d in the same order as the sorted_l.

Expected output:

In [1201]: d
Out[1201]: [[500], [100], [200]]

What is the best way to do this?

1 Answers

Below is the solution with help from @juanpa.arrivillaga :

In [1272]: import operator
In [1273]: key = operator.itemgetter(0, 1, 2)

# Here param key, lets you sort `l` with your own function.
In [1275]: sorted_l,sorted_d = zip(*sorted(zip(l, d), key=lambda x: key(x[0])))

In [1276]: sorted_l
Out[1276]: 
(['Cancer A', 'Ecog 0', 'Fill 0'],
 ['Cancer A', 'Ecog 9', 'Fill 6'],
 ['Cancer B', 'Ecog 1', 'Fill 1'])

In [1277]: sorted_d
Out[1277]: ([500], [100], [200])
Related