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

前端 未结 5 720
刺人心
刺人心 2021-01-19 19:33

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 u

相关标签:
5条回答
  • 2021-01-19 20:18
    complex_out = []
    for row in out:
        comp_row = [complex(x) for x in row]
        complex_out.append(comp_row)
    
    0 讨论(0)
  • 2021-01-19 20:22

    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)
    
    0 讨论(0)
  • 2021-01-19 20:23
    >>> c = ['(37470-880j)','(35093-791j)','(33920-981j)']
    >>> map(complex, c)
    [(37470-880j), (35093-791j), (33920-981j)]
    
    0 讨论(0)
  • 2021-01-19 20:23

    I think each method above is bit complex

    Easiest Way is this

    In [1]: complex_num = '-2+3j'
    
    In [2]: complex(complex_num)
    Out[2]: (-2+3j)
    
    0 讨论(0)
  • 2021-01-19 20:24

    CSV docs say:

    Note that complex numbers are written out surrounded by parens. This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).

    This should convert elements in 'out' to complex numbers from the string types, which is the simplest solution given your existing code with ease of handling non-complex entries.

     for i,row in enumerate(out):
          j,entry in enumerate(row):
              try:
                   out[i][j] = complex(out[i][entry])
              except ValueError:
                   # Print here if you want to know something bad happened
                   pass
    

    Otherwise using map(complex, row) on each row takes fewer lines.

     for i,row in enumerate(out):
          out[i] = map(complex, row)
    
    0 讨论(0)
提交回复
热议问题