[Python] how does lambda-function work when sorting with conditions?

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    Task: Write a program that sorts a string of numbers received from the user in the following way: Negative numbers come after positive numbers; Both positive and negative numbers are sorted in ascending order.

    Input example:
    -6 -1 3 -5 -15 4 1 9 8 6 -3 -4 12 -10 7
    Output:
    1 3 4 6 7 8 9 12 -15 -10 -6 -5 -4 -3 -1

    The solution contains the following code:

    lst=list(map(int,input().split()))
    print(*sorted(lst,key= lambda x: 0 if x==0 else -1/x))


    Why are the conditions like that? I especially don't understand "else -1/x"

    I just started learning anonymous functions and it's hard to understand them.

    Continue reading...

Compartilhe esta Página