Python - Sort string order by order of increasing number of letters

Asked

Viewed 5,282 times

1

Having the following list:

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

And wanting to order it by order quantity of increasing letters.

I am not achieving the desired result. Here’s what I got:

    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 exactly what I wanted...

Someone who can help me please?

Thank you,

  • It’s not the "length" of the name you want?

1 answer

3


Right now you are making an alphabetical order ordering, and from what I understand you want to sort by the string size of each element, so:

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 first parameter of the Sorted you will define the list you want to sort and in the second a function that will be executed for each element of the list.

Reference - Sorting Basics

  • Thank you very much! That was it!! I didn’t remember the "key=Len"

  • You’re welcome, I’m learning too ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.