0

I have a list

list1 = [[a,   e,   o,   i,   u], 
     [3.0, 2.0, 1.0, 5.0, 4.0], 
     [5.1, 4.7, 2.5, 3.2, 1.1]]

I want to sort this list based on the 2nd list. i.e. the middle one. The result should be as follows

sorted_list1 = [[o,   e,   a,   u,   i],
            [1.0, 2.0, 3.0, 4.0, 5.0],
            [2.5, 4.7, 5.1, 1.1, 3.2]

Please mention the supporting import modules as well if required.

Note: I have equal number of elements in each list.

4
  • zip(*sorted(zip(*list1), key=lambda c: c[1])) should do this (transpose, sort on middle column, transpose again). You may need to add list() in Python 3, or wrap in [list(r) for r in ...] to output a list of lists again. Commented Apr 24, 2017 at 11:56
  • Thanks. This answer works. Is python able to sort only based on columns? Commented Apr 24, 2017 at 12:02
  • 1
    sorting applies to a single sequence. You have 3 sequences, so I combined them into one sequence containing tuples of 3 values each, then reverse the process after sorting. Commented Apr 24, 2017 at 12:03
  • In Python 3.6 you can also do [*map(list, zip(*sorted(zip(*list1), key=lambda c: c[1])))] if you really need a list of lists instead of a list of tuples. Commented Apr 24, 2017 at 12:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.