Python - Sort list strings by number of ascending letters

1

Having the following list:

lista_nomes =['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre']

And wanting to sort it by increasing number of letters.

Now, I'm not getting the desired result. What I have is the following:

    lista_nomes =['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre']
    lista_nomes.sort()

    print (lista_nomes)

*OUTPUT-> ['Andre', 'Antonio', 'Diogo', 'Jasmim', 'Laura', 'Lu', 'Manuel', 'Maria', 'Miguel', 'Pancrácio', 'Ricardo', 'Silvia']*

This is not quite what I wanted ...

Someone who can help me please?

Thanks,

    
asked by anonymous 02.05.2018 / 10:24

1 answer

3

At this point you are doing an alphabetical sort order, and for that I understand you want to sort by the string size of each element, therefore:

lista_nomes =['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 

'Pancracio', 'Diogo', 'Ricardo', 'Miguel', 'Andre']

lista_ordenada = sorted(lista_nomes, key=len)

print(lista_ordenada)

In the 1st parameter of the sorted will define the list that you want to sort and in the second a function that will be executed for each element of the list.

Reference - Sorting Basics

    
02.05.2018 / 10:50