[Python] How to sort a list of lists based on a specific order in Python?

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to sort a list of lists in a specific way. The example will explain everything clearly.

    For example, if the input is:

    [[3, 4, 3],[2, 6, 2],[2, 5, 6]]


    The output should be:

    [[2, 5, 6], [2, 6, 2], [3, 4, 3]]


    Basically, I want to sort the list based on the first element of each list, and then, in second priority, based on the second element of each list. So that if 2 lists have the same element at their index 0 they are sorted based on the element at index 1.

    I managed to sort it based on the first element using this line of code:

    mix_data_1 = sorted(mix_data, key=lambda x: x[0])


    But I am unable to fund a way to then sort it on top by the second element. How could I do this, without breaking the sorting of the list based on the first element? Also, in the list the elements aren't numbers but strings, I used numbers because I thought it would be easier to understand.

    Continue reading...

Compartilhe esta Página