How to sort the outer and inner sublist of a neste

2019-02-19 13:29发布

问题:

First of all, apologies if this too naive (I am a beginner). I have the following type of list of lists, which I would like to first sort by the last member of the inner list in ascending order:

data =  [[1, .45, 0], [2, .49, 2], [3, .98, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2] ]

I accomplish this by using : sorted(data,key=operator.itemgetter(2),reverse = True), which gives me:

[[1, .45, 0], [3, .98, 0],[4, .82, 1], [5, .77, 1], [2, .49, 2], [6, .98, 2]]

Now, I would like to sort within the sub-lists i.e. first sort the list with its last member as '0' using the middle member as the key, in descending order. Then sort the sub-list with '1' as its last member and so on. Note that number of elements in each sub-list are different and are not know. The final list should look like this:

[[3, .98, 0],[1, .45, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2],[2, .49, 2] ]

The list is actually quite huge, therefore I am looking for an efficient implementation. Any guidance would be appreciated !

回答1:

>>> data =  [[1, .45, 0], [2, .49, 2], [3, .98, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2] ]
>>> sorted(data, key=lambda x:(x[2], -x[1]))
[[3, 0.98, 0], [1, 0.45, 0], [4, 0.82, 1], [5, 0.77, 1], [6, 0.98, 2], [2, 0.49, 2]]

You can add extra terms to the lambda as required



回答2:

You can pass sorted multiple keys:

data =  [[1, .45, 0], [2, .49, 2], [3, .98, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2] ]
sorted(data, key=lambda x: (x[2], -x[1]))

[[3, 0.98, 0],
 [1, 0.45, 0],
 [4, 0.82, 1],
 [5, 0.77, 1],
 [6, 0.98, 2],
 [2, 0.49, 2]]