w3resource

NumPy: Sort a given complex array using the real part first, then the imaginary part

NumPy Sorting and Searching: Exercise-6 with Solution

Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.

Sample Solution:

Python Code:

import numpy as np
complex_num = [1 + 2j, 3 - 1j, 3 - 2j, 4 - 3j, 3 + 5j]
print("Original array:")
print(complex_num)
print("\nSorted a given complex array using the real part first, then the imaginary part.")
print(np.sort_complex(complex_num))

Sample Output:

Original array:
[(1+2j), (3-1j), (3-2j), (4-3j), (3+5j)]

Sorted a given complex array using the real part first, then the imaginary part.
[1.+2.j 3.-2.j 3.-1.j 3.+5.j 4.-3.j]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to get the indices of the sorted elements of a given array.
Next: Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice).

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: Find the number of occurrence of each values in an iterable

It returns True only if two values point to same object.