Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

converting an array of arrays of floats to complex numbers

I’ve got an array of arrays each containing the two parts of a complex number, like this:

parts = [[1, 2], [3, 4], [5, 6]]

How do I convert them to an array of complex numbers, like this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

munged = [1+2i, 3+4i, 5+6i]

>Solution :

This should work

parts = [[1, 2], [3, 4], [5, 6]]

complex_list = [complex(x[0], x[1]) for x in parts]
[(1+2j), (3+4j), (5+6j)]

Note: Each complex number will be a tuple (1+2j). If you need it to be a string '1+2j'; use:

complex_list = [str(complex(x[0], x[1]))[1:-1] for x in parts]
['1+2j', '3+4j', '5+6j']

If you need the j to be an i and the entire thing as a string, use this:

complex_list = [f"{x[0]}+{x[1]}i" for x in parts]
['1+2i', '3+4i', '5+6i']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading