string - Want to convert text file of complex numbers to a list of numbers in Python -


i have text file of complex numbers called output.txt in form:

[-3.74483279909056 + 2.54872970226369*i] [-3.64042002652517 + 0.733996349939531*i] [-3.50037473491252 + 2.83784532111642*i] [-3.80592861109028 + 3.50296053533826*i] [-4.90750592116062 + 1.24920836601026*i] [-3.82560512449716 + 1.34414866823615*i] etc... 

i want create list these (read in string in python) of complex numbers.

here code:

data = [line.strip() line in open("output.txt", 'r')] in data:     m = map(complex,i) 

however, i'm getting error:

valueerror: complex() arg malformed string 

any appreciated.

from information, complex builtin function:

>>> help(complex) class complex(object)  |  complex(real[, imag]) -> complex number  |  |  create complex number real part , optional imaginary part.  |  equivalent (real + imag*1j) imag defaults 0. 

so need format string properly, , pass real , imaginary parts separate arguments.


example:

num = "[-3.74483279909056 + 2.54872970226369*i]".translate(none, '[]*i').split(none, 1) real, im = num print real, im >>> -3.74483279909056 + 2.54872970226369 im = im.replace(" ", "") # remove whitespace c = complex(float(real), float(im)) print c >>> (-3.74483279909+2.54872970226j) 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -