Sort tuple by key in Python 3

Asked

Viewed 1,178 times

0

I have a lista_tupla = [(1, [1, 2, 3, 4]), (2, [5, 6, 7]), (3, [7, 8, 9]), (3, [10, 11, 12]), (4, [13, 14, 15])] where the first index of each tuple is a key and the second index is a list as above.

I would like to know: how do I order it by key? I tried the following command:

lista_tupla_ordenada = lista_tupla.sort(key=lambda, x: x[1])

But it didn’t work. Return:

>>> lista_tupla_ordenada = lista_tupla.sort(key=lambda, x: x[1])
  File "<stdin>", line 1
    lista_tupla_ordenada = lista_tupla.sort(key=lambda, x: x[1])
                                                      ^
SyntaxError: invalid syntax

How can I fix this?

PS: Yes, I need every duplicate key in my tuple :P

  • 1

    As the answer says, this case you don’t need the lambda - because you’re ordering straight through the first item of each tuple. But what’s wrong there is the comma after the word lambda the correct would be 'lambda x: x[0]- sem,depois de lambda - e tomando o elemento0(não elemento1`) of each tuple.

1 answer

1


You’ve got the hardest, now you’re all:
Sort increasingly (smaller to larger):

lista_tupla_ordenada = sorted(lista_tupla)

Sort decreasingly (higher to lower):

lista_tupla_ordenada = sorted(lista_tupla, reverse=True)

Browser other questions tagged

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