Sort list of lists

Asked

Viewed 792 times

1

I have the following list of lists:

lista = [['a', '1'], ['c', '3'], ['b', '2']]

And I want to sort this list according to the numbers, which means I want it to stay that way:

listaOrdenada = [['a','1'], ['b','2'], ['c','3']]

2 answers

0


You can use the function sorted and pass as second parameter to key ordination to be made

listaOrdenada = sorted(lista, key = lambda x: x[1])
  • Thank you, that’s right! :)

  • And if I have: lista = [['ana','1'], ['anita','2'], ['rita','2']] in this case I want to sort the list according to the numbers, but since there are 2 lists with the number '2', in this case I wanted to sort these 2 lists by alphabetical order of the name, with an if possibly... know how to do this @jbueno ?

  • I do know @Stinrose Open a new question, this is a new subject

0

#!/usr/bin/python

listaOrdenada =  [['a','1'], ['c','3'], ['b','2']]
print "List : ", sorted(listaOrdenada,key=lambda l:l[1], reverse=False)

You can use lambda too. :)

  • The PA wants to organize by the second element, not by the first.

  • 1

    in fact, I didn’t notice this detail. editing here.

  • Now you’re right +1

Browser other questions tagged

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