简体   繁体   English

想要将复数的文本文件转换为Python中的数字列表

[英]Want to convert text file of complex numbers to a list of numbers in Python

I have a text file of complex numbers called output.txt in the form: 我有一个格式为复数的文本文件,称为output.txt

[-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 to create a list from these (read in as a string in Python) of complex numbers. 我想从中创建一个复数列表(在Python中以字符串形式读取)。

Here is my code: 这是我的代码:

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

However, I'm getting the error: 但是,我得到了错误:

ValueError: complex() arg is a malformed string

Any help is appreciated. 任何帮助表示赞赏。

From the help information, for the complex builtin function: 从帮助信息中,获取complex内置功能:

>>> help(complex)
class complex(object)
 |  complex(real[, imag]) -> complex number
 |
 |  Create a complex number from a real part and an optional imaginary part.
 |  This is equivalent to (real + imag*1j) where imag defaults to 0.

So you need to format the string properly, and pass the real and imaginary parts as 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)

Try this: 尝试这个:

numbers = []
with open("output.txt", 'r') as data:
    for line in data.splitlines():
        parts = line.split('+')
        real, imag = tuple( parts[0].strip(' ['), parts[1].strip(' *I]') )
        numbers.append(complex(float(real), float(imag)))

The problem with your original approach is that your input file contains lines of text that complex() does not know how to process. 原始方法的问题在于您的输入文件包含complex()不知道如何处理的文本行。 We first need to break each line down to a pair of numbers - real and imag. 我们首先需要将每一行分解为一对数字-实数和imag。 To do that, we need to do a little string manipulation (split and strip). 为此,我们需要进行一些字符串操作(拆分和剥离)。 Finally, we convert the real and imag strings to floats as we pass them into the complex() function. 最后,当我们将实数和imag字符串传递给complex()函数时,将它们转换为浮点数。

这是创建复杂值列表的简洁方法(基于dal102答案):

data = [complex(*map(float,line.translate(None, ' []*I').split('+'))) for line in open("output.txt")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM