I\'m trying to write code which imports and exports lists of complex numbers in Python. So far I\'m attempting this using the csv module. I\'ve exported the data to a file u
complex_out = []
for row in out:
comp_row = [complex(x) for x in row]
complex_out.append(comp_row)
Just pass the string to complex():
>>> complex('(37470-880j)')
(37470-880j)
Like int() it takes a string representation of a complex number and parses that. You can use map() to do so for a list:
map(complex, row)
>>> c = ['(37470-880j)','(35093-791j)','(33920-981j)']
>>> map(complex, c)
[(37470-880j), (35093-791j), (33920-981j)]
I think each method above is bit complex
Easiest Way is this
In [1]: complex_num = '-2+3j'
In [2]: complex(complex_num)
Out[2]: (-2+3j)
CSV docs say:
Note that complex numbers are written out surrounded by parens. This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).
This should convert elements in 'out' to complex numbers from the string types, which is the simplest solution given your existing code with ease of handling non-complex entries.
for i,row in enumerate(out):
j,entry in enumerate(row):
try:
out[i][j] = complex(out[i][entry])
except ValueError:
# Print here if you want to know something bad happened
pass
Otherwise using map(complex, row) on each row takes fewer lines.
for i,row in enumerate(out):
out[i] = map(complex, row)