[Python] Why is the sorting result of Python lists so strange? [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    The code is as follows, using key function to count the number of times each element appears in the list:

    input_list = list('aaddccdc')
    input_list.sort(key=lambda i: (-input_list.count(i), ord(i)))
    print(input_list)


    We get the result in unexpected order

    ['a', 'a', 'c', 'c', 'c', 'd', 'd', 'd']


    If it is modified so that we use a copy in the key function

    input_list = list('aaddccdc')

    snapshot = input_list.copy()
    input_list.sort(key=lambda i: (-snapshot.count(i), ord(i)))

    print(input_list)


    We get the different, expected order

    ['c', 'c', 'c', 'd', 'd', 'd', 'a', 'a']


    Why is that?

    Continue reading...

Compartilhe esta Página