Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to a turn a list of strings into complex numbers in python?

Tags:

python

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.

like image 260
new_sysadmin Avatar asked Dec 01 '22 21:12

new_sysadmin


2 Answers

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)
like image 163
Martijn Pieters Avatar answered Dec 17 '22 15:12

Martijn Pieters


>>> c = ['(37470-880j)','(35093-791j)','(33920-981j)']
>>> map(complex, c)
[(37470-880j), (35093-791j), (33920-981j)]
like image 22
applicative_functor Avatar answered Dec 17 '22 15:12

applicative_functor