Search code examples
pythonpython-3.xcomplex-numbers

Converting str numbers to in two different lists to a list of Complex numbers in python 3.8


I am new to python, i will re-edit and make it clear :) thanks for investing your time.

I have two different lists with string values (as shown below):

  1. A list with 1600 real numbers: ['-1,03E+01' '-1,26E+01' .......]

  2. Another list with 1600 imaginary values: [ '-1,25E+01' '-1,02E+01' .... ]

These are directly imported from touchstone file. so, i do not see letter j for imaginary. i don't know y.

  • First i have to change the type of the value from 'str' to float for further calculation.
  • Then append them into a list as complex value like [[-1,03E+01 -1,25E+01 j] [-1,26E+01-1,02E+01j].......]

Solution

  • Since you have edited your question to say that your numbers are actually represented by strings of float values (your second list of your second example of [7j, 8j, et.c] makes this very confusing, though):

    l1 = ['-1,03E+01', '-1,26E+01']
    
    l2 = ['-1,25E+01', '-1,02E+01']
    
    [complex(float(a), float(b)) for a, b in zip(l1, l2)]
    

    Original answer:

    For two lists l1 containing the real values and l2 containing the imaginary values (as you describe them, but I think you mean coefficients):

    [complex(a,b) for a, b in zip(l1, l2)] 
    

    This answer will get you a list of complex values:

    [(1+7j), (2+8j), (3+9j), (4+10j), (5+11j), (6+12j)]. 
    

    As you indicated in your comment below, if you want it to be:

    [ [(1+7j)] [(2+8j)] [(3+9j)] [(4+10j)] [(5+11j)] [(6+12j)] ] 
    

    as indicated in your question, then change it to:

    [[complex(a, b)] for a, b in zip(l1,l2)]