0

I want to sort the list of list based on the two factors:

  • PRIMARILY: list has to be sorted in ascending order based on the second element of each list in the list
  • If there are cases wheres various list has same second elements then for those particular lists sorting has to be done in ascending order based on first element.

data_input: [ [78, 10], [130, 0], [10, 1], [100, 100], [2, 2], [1, 99], [100, 0] ]

for sorting based on first criterion I am using this code

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

but cannot think of any way to implement second criterion as well

Desired output :

  • data_input: [ [100, 0], [130, 0], [10, 1], [2, 2], [78, 10], [1, 99], [100, 100] ]*
p.ram
  • 109
  • 10

2 Answers2

2

Use a tuple as key argument to sorted:

data_input = [ [78, 10], [130, 0], [10, 1], [100, 100], [2, 2], [1, 99], [100, 0] ]

print(sorted(data_input, key=lambda x: (x[1], x[0])))
# [[100, 0], [130, 0], [10, 1], [2, 2], [78, 10], [1, 99], [100, 100]]

This basically asks Python to sort by x[1] and for same x[1], sort by x[0].

Austin
  • 25,759
  • 4
  • 25
  • 48
  • Could you please explain how `key = lambda x: (x[1], x[0])` is working? – p.ram Jun 12 '19 at 17:29
  • `key` argument of `sorted` can be used to tell on what basis you need the sort to take place. `(x[1], x[0])` part tells to sort by `x[1]` (second element in each sublist) and for same matching `x[1]`s (same second elements), sort by `x[0]` (first element in each sublist. – Austin Jun 12 '19 at 17:33
  • @ Austin for this particular example how can I sort first elements in descending order (keeping second element as primary for sorting in ascending order) – p.ram Jun 12 '19 at 18:02
  • 1
    Use: `key=lambda x: (x[1], -x[0])`. – Austin Jun 12 '19 at 18:02
2

You can use sorted with itemgetter to specify the order in which items from the sublists must be fetched:

from operator import itemgetter

sorted(data_input, key=itemgetter(1,0))
# [[100, 0], [130, 0], [10, 1], [2, 2], [78, 10], [1, 99], [100, 100]]
yatu
  • 86,083
  • 12
  • 84
  • 139
  • is `key=itemgetter(1,0)` is sorting the list first on the basis of `1` index of inner list then `0` index? – p.ram Jun 12 '19 at 17:37
  • Yes that's right @aman – yatu Jun 12 '19 at 17:38
  • using this method and for this particular example, how can I sort the first element in reverse order that is descending order? – p.ram Jun 12 '19 at 17:55
  • For this purpose you'd need a lambda function, and you'd have to take the negative of the first item so that it is sorted in inverse order – yatu Jun 12 '19 at 19:29