mk6man
mk6man

Reputation: 43

Sort a sorted nested list by another index

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?

Upvotes: 1

Views: 522

Answers (3)

Mechanic Pig
Mechanic Pig

Reputation: 7736

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

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195418

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

Upvotes: 2

Chandler Bong
Chandler Bong

Reputation: 461

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

Upvotes: 0

Related Questions