Home > Software engineering >  Sorting list by the inner elements in Python?
Sorting list by the inner elements in Python?

Time:10-02

How that list can be sorted by the inner list elements?

my_list = [[False, 3, 82],[True,15,34], [False,22, 33], [True,2, 5], [False,1,67], [False, 22, 44], [True, 6, 99], [True, 14, 34], [False, 2, 82]]

I need a list at the final like that;

my_list = [[True,2, 5], [True, 2, 99], [True, 14, 34],[True,15,34], [False, 1,67], [False, 2, 82], [False, 3, 44], [False,3, 88], [[False, 22, 44]]

It will check the first elements of the inner lists, if there are more than one "True", it will check and sort the second elements. If there are the same numbers, than it will check the third elements.

CodePudding user response:

Use the key parameter of sorted:

import pprint

my_list = [[False, 3, 82], [True, 15, 34], [False, 22, 33],
           [True, 2, 5], [False, 1, 67], [False, 22, 44],
           [True, 6, 99], [True, 14, 34], [False, 2, 82]]


res = sorted(my_list, key=lambda x: (not x[0], x[1], x[2]))
pprint.pprint(res)

Output

[[True, 2, 5],
 [True, 6, 99],
 [True, 14, 34],
 [True, 15, 34],
 [False, 1, 67],
 [False, 2, 82],
 [False, 3, 82],
 [False, 22, 33],
 [False, 22, 44]]

The idea of:

lambda x: (not x[0], x[1], x[2])

is to negate the first argument to put the inner list with True first, then use the normal int comparison for the rest of the elements.

CodePudding user response:

You can simply do it by sorting your list thrice based on key as follow :-

  1. First sort your list based on the last element of each sub-list.

  2. then sort on basis of middle element.

  3. Sort based on first element and in reverse order. That's it.

    my_list = [[False, 3, 82],[True,15,34], [False,22, 33], [True,2, 5], [False,1,67], [False, 22, 44], [True, 6, 99], [True, 14, 34], [False, 2, 82]]

    my_list.sort(key = lambda x : x[2])

    my_list.sort(key = lambda x : x[1])

    my_list.sort(key = lambda x : x[0], reverse = True)

    print(my_list)

or you can use one liner for the same job as follow :

my_list.sort(key = lambda x : (not x[0], x[1], x[2]))

advantage of using sort function instead of sorted is that it is in place so no extra memory is required.

  • Related