1

I have a list in python as follows,

 l =    [['4K', ['read', '10'], ['rand', '70']],
        ['64K', ['read', '15'], ['rand', '0']],
        ['64K', ['read', '0'], ['rand', '0']],
        ['4K', ['read', '60'], ['rand', '100']],
        ['4K', ['read', '50'], ['rand', '0']]]

If temp = ['4K', ['read', '10'], ['rand', '100'] I first want to sort based on temp[2][1], after which I want to sort the list further without modifying the previous sort with respect to temp[1][1]. I want the end result to be something like follows,

res = [['64K', ['read', '0'], ['rand', '0']],
       ['64K', ['read', '15'], ['rand', '0']],
       ['4K', ['read', '50'], ['rand', '0']],
       ['4K', ['read', '10'], ['rand', '70'],
       ['4K', ['read', '60'], ['rand', '100']
      ]

In res above the priority is first given to rand which is sorted first, after which read is sorted with the sorted rand. I have tried things like l.sort(key=lambda x: int(x[2][1])) which first sorts the rand, but sorting the same l further does not give expected output as the previous sort is not remembered. Is there an easy way to do this? Or is the only way to this would be to split the list further with same rand and then sort and merge all together at the end?

Chanda Korat
  • 2,453
  • 2
  • 19
  • 23
nidHi
  • 833
  • 3
  • 10
  • 21
  • 1
    @NickA I think the official term is "stable sort", which Python's built-in sort [already is](http://stackoverflow.com/a/1915418/1639625). (The advice about applying the criteria backwards is valid, of course) – tobias_k May 15 '17 at 12:03
  • @tobias_k I've moved our discussion to an answer below – Nick is tired May 15 '17 at 12:12

2 Answers2

4
l.sort(key=lambda x: (int(x[2][1]), int(x[1][1])))

Does exactly what you want. Tuples are sorted giving priority in order.

Oersted
  • 175
  • 2
  • 8
1

@Oersted's answer is the way to go however the general rule when sorting by multiple criteria is to sort using a stable sort(which pythons list.sort is) and to sort through the criteria backwards, this rule can be used anywhere from sorting in excel to sorting a web based table, in this case you would use:

l.sort(key=lambda x: int(x[1][1]))
l.sort(key=lambda x: int(x[2][1]))
Community
  • 1
  • 1
Nick is tired
  • 6,860
  • 20
  • 39
  • 51