1

How can I sort an already sorted list by another index?

example: I have a list that is sorted by index 1.

[["DOG", 5], ["DAM",5], ["DAN", 5], ["BAT", 4], ["CAT", 3], ["MAN", 2]]

I want the following output:

[["DAM", 5], ["DAN",5], ["DOG", 5], ["BAT", 4], ["CAT", 3], ["MAN", 2]]

The list has been sorted by index 1. If an index 1 has multiple occurences in the list, how should I sort index 0 so that the overall nested list retains its order in terms of index 0?

Chandler Bong
  • 461
  • 1
  • 3
  • 18
mk6man
  • 43
  • 4

3 Answers3

2

You can construct custom key function that returns 2-item tuples (first second element (negative) and then first element):

lst = [["DOG", 5], ["DAM", 5], ["DAN", 5], ["BAT", 4], ["CAT", 3], ["MAN", 2]]

print(sorted(lst, key=lambda k: (-k[1], k[0])))

Prints:

[["DAM", 5], ["DAN", 5], ["DOG", 5], ["BAT", 4], ["CAT", 3], ["MAN", 2]]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Since the list has been sorted once, you can use itertools.groupby:

>>> from itertools import groupby, chain
>>> from operator import itemgetter
>>> list(chain.from_iterable(sorted(group) for _, group in groupby(lst, key=itemgetter(1))))
[['DAM', 5], ['DAN', 5], ['DOG', 5], ['BAT', 4], ['CAT', 3], ['MAN', 2]]
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
0

I am not sure what you mean. But, you can always sort a list based on a key.

l = ['ali', 'mohamed', 'ahmed']
l.sort(key = lambda char: char[2])   # this will sort the list based on the 
                                      #charachter at index 2

output: ['mohamed', 'ali', 'ahmed']

You can also sort the list in descending or ascending order.

l.sort(key = lambda char: char[2], reverse = True)    

output: ['ahmed', 'ali', 'mohamed']

Chandler Bong
  • 461
  • 1
  • 3
  • 18
  • This is not what he means. He means to sort by multiple criteria. First the second index in reverse, then the first one not in reverse. – Daniel F Aug 20 '22 at 20:43