Search code examples
pythonsortingcomplex-numbers

Sort list of complex numbers and get sorting indexes


I need to sort a list of complex numbers by the imaginary parts. I found the solution on the question “sorting list of complex numbers”.

Simply using the sorted command with the appropriate key:

list_ordered = sorted(list, key=lambda x: x.imag) 

I'd also like to get back the sorting indexes. Another existing solution doesn't work in the case of complex numbers. Is there an elegant solution to extract the indexes in my case?

Thanks!


Solution

  • The second answer to the question you linked can easily be adapted:

    complexes = [1, 2+3j, 1-2j, 6+1j]
    [i[0] for i in sorted(enumerate(complexes), key=lambda x:x[1].imag)]
    
    # [2, 0, 3, 1]