Skip to content
Advertisement

Sorting list by the inner elements in Python?

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement