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?
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']