-1

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!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Rocco B.
  • 117
  • 1
  • 12
  • What are "sorting indexes"? You have multiple lists (input, output, intermediate in some algorithms) involved, and this could refer to the indexes of items in any of them. Clarify your question. – jpmc26 Sep 19 '18 at 16:38

1 Answers1

1

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]
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50