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 using:
spamWriter = csv.writer(open('data.csv', 'wb')
spamWriter.writerow(complex_data)
Where complex data is a list numbers generated by the complex(re,im) function. Ex:
print complex_data
[(37470-880j),(35093-791j),(33920-981j),(28579-789j),(48002-574j),(46607-2317j),(42353-1557j),(45166-2520j),(45594-232j),(41149+561j)]
To then import this at a later time, I try the following:
mycsv = csv.reader(open('data.csv', 'rb'))
out = list(mycsv)
print out
[['(37470-880j)','(35093-791j)','(33920-981j)','(28579-789j)','(48002-574j)','(46607-2317j)','(42353-1557j)','(45166-2520j)','(45594-232j)','(41149+561j)']]
(Note that this is a list of lists, I just happened to use only one row for the example.)
I now need to turn this into complex numbers rather than strings. I think there should be a way to do this with mapping as in this question, but I couldn't figure out how to make it work. Any help would be appreciated!
Alternatively, if there's any easier way to import/export complex-valued data that I don't know of, I'd be happy to try something else entirely.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With