1

I want to sort a python list which contains numbers (say l1), and use the indices (sorting order) of this list to rearrange the elements of two different lists (l2 and l3). I want to achieve this using standard python libraries (not pandas). I am using python 2.7.

For example, let say:

l1 = [2,4,5,1]
l2 = ['aa', 'bb', 'cc', 'dd']
l3= ['a_a', 'b_b', 'c_c', 'd_d']

Here, I would want to sort l1 in descending order such that l1_sorted = [5,4,2,1].

The others lists (l2 and l3) would get rearranged following the indices of sorting in l1 (l1_sorted). In the above example, we should have:

l2_sorted = ['cc', 'bb', 'aa', 'dd']
l3_sorted = ['c_c', 'b_b', 'a_a', 'd_d']

At present, I am using the sorted function of Python (l1_sorted = sorted(l1, reverse=True) ) . But that only gives me l1_sorted.

How can I achieve the full functionality that I desire (i.e. l2_sorted and l3_sorted)?

Joe Iddon
  • 19,256
  • 7
  • 31
  • 50
Ji Won Song
  • 110
  • 2
  • 9

1 Answers1

5

Zip them together, sort, then unpack:

zipd = sorted(zip(l1,l2,l3), key=lambda t:-t[0])
l2_sorted = [t[1] for t in zipd] #['cc', 'bb', 'aa', 'dd']
l3_sorted = [t[2] for t in zipd] #['c_c', 'b_b', 'a_a', 'd_d']
Joe Iddon
  • 19,256
  • 7
  • 31
  • 50