Home > Software design >  Sort a sorted nested list by another index?
Sort a sorted nested list by another index?

Time:08-20

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?

CodePudding user response:

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']

CodePudding user response:

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]]
  • Related