Getting the real and imaginary parts of complex numbers stored as strings in a list

I did this to restore the first part of the line, for example: "13" from "13 + i":

l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
l2 = [i.split('+')[0] for i in l1]
l2 = list(map(int, l2))

It worked, and then I want "1" from "13 + i", but it's more complicated since the "i" in the line did not get the coefficient "1".

I should get:

[1, 4, 2, 4, 1, 2, 4]

ie, only the imaginary part of the complex number in the array.

Any idea to help me solve this problem?

+4
source share
2 answers

Python has a way to solve complex numbers; it actually has a type for them ( <class 'complex'>). As a result, and to avoid having to reinvent the wheel, I highly recommend using this.

, ( strings complex). Python , 'j', 'i'.

l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
l1 = [complex(x.replace('i', 'j')) for x in l1]

# if you are curious how they look like
print(l1)
# -> [(13+1j), (1+4j), ...]

, , .real .imag complex list-compehensions.

real_parts = [value.real for value in l1]
print(real_parts) 
# -> [13.0, 1.0, 3.0, 11.0, 5.0, 10.0, 5.0]

imaginary_parts = [value.imag for value in l1]
print(imaginary_parts)
# -> [1.0, 4.0, 2.0, 4.0, 1.0, 2.0, 4.0]

, (, ). [int(value.real) for value in l1] int.

, - , , , , , , , . , 4j ( ) 1-j ( , .split('+')[0] ) ..

+5

python j .

,

i=['13+i','1+4i','3+2i','11+4i','5+i','10+2i','5+4i']
real_parts=[ complex(x.replace("i", "j")).real for x in i]
imaginary_parts=[ complex(x.replace("i", "j")).imag for x in i ]

, .

0

Source: https://habr.com/ru/post/1692521/


All Articles