Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python.. Accessing the default sort function?

Python Code:

b=['six', 'small', 'he', 'foxes', 'saw']
b.sort(key=len)
b

Output:

['he', 'six', 'saw', 'small', 'foxes']

In the above code, I sorted by length of elements and got the above output.

The output I want looks like this: ['he', 'saw', 'six', 'small', 'foxes']

So I want the first sort by length. Then for elements with the same length I want to sort alphabetically.

My question: Is there a way to do it without writing a custom function? Maybe something like this:

b.sort(key=[len,sorted]) # this doesn't work but I think it explains the idea.

Thanks!

like image 448
DataCapitalist Avatar asked Dec 06 '22 10:12

DataCapitalist


1 Answers

We can use a compound sorting key, first sort by length, second lexicographically. We do this by creating a tuple, because tuples will naturally sort using the elements in the order they appear.

b = ['six', 'small', 'he', 'foxes', 'saw']
b.sort(key=lambda s: (len(s), s))

For the record, the above results in this sorted list::

['he', 'saw', 'six', 'foxes', 'small']

Which is the correct order as stipulated in the question (but the sample output in the question is wrong, so please be aware of it before downvoting!)

like image 170
Óscar López Avatar answered Dec 25 '22 11:12

Óscar López