Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort by length of string followed by alphabetical order?

Tags:

python

sorting

I'm currently new to python and got stuck at this question, can't seem to find the proper answer.

question:Given a list of words, return a list with the same words in order of length (longest to shortest), the second sort criteria should be alphabetical. Hint: you need think of two functions.

This is what I have so far:

def bylength(word1,word2):     return len(word2)-len(word1)  def sortlist(a):     a.sort(cmp=bylength)     return a 

it sorts by length but I don't know how to apply the second criteria to this sort, which is by alphabetical descending.

like image 467
Adrian Avatar asked Jan 11 '11 15:01

Adrian


People also ask

How do you sort a string by length?

To sort the array by its string length, we can use the Array. sort() method by passing compare function as an argument. If the compare function return value is a. length - b.

How do you sort a list of elements in alphabetical order?

Select the list you want to sort. Go to Home > Sort. Set Sort by to Paragraphs and Text. Choose Ascending (A to Z) or Descending (Z to A).


1 Answers

You can do it in two steps like this:

the_list.sort() # sorts normally by alphabetical order the_list.sort(key=len, reverse=True) # sorts by descending length 

Python's sort is stable, which means that sorting the list by length leaves the elements in alphabetical order when the length is equal.

You can also do it like this:

the_list.sort(key=lambda item: (-len(item), item)) 

Generally you never need cmp, it was even removed in Python3. key is much easier to use.

like image 161
Jochen Ritzel Avatar answered Sep 19 '22 21:09

Jochen Ritzel