正在尝试将字符串转换为复数列表

2024-10-01 02:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将字符串转换为复数列表。(如果您阅读它时不带引号,那么它将是一个复数列表。)我已经编写了一个函数来执行此操作,但我得到了以下错误:

Traceback (most recent call last):
    File "complex.py", line 26, in <module>
        print(listCmplx('[1.111 + 2.222j, 3.333 + 4.444j]'))
    File "complex.py", line 10, in listCmplx
        while (not isDigit(listIn[count])) and (listIn[count] != '.'):
IndexError: string index out of range

我做错了什么

def isDigit(char):
    return char in '0123456789'

def listCmplx(listIn):
    listOut = []
    count = 0
    real = '0'
    imag = '0'
    while count < len(listIn):
        while (not isDigit(listIn[count])) and (listIn[count] != '.'):
            count += 1
        start = count
        while (isDigit(listIn[count])) or (listIn[count] == '.'):
            count += 1
        end = count
        if listIn[count] == 'j':
            imag = listIn[start:end]
        else:
            real = listIn[start:end]
        if listIn[count] == ',':
            listOut += [float(real) + float(imag) * 1j]
            real = '0'
            imag = '0'
    return listOut

print(listCmplx('[1.111 + 2.222j, 3.333 + 4.444j]'))

先谢谢你


Tags: in列表countrealstartfileend复数
2条回答

令人惊讶的是,这是Python不需要编写任何函数就可以做到的,它内置了复数类

listIn = '1.111 + 2.222j, 3.333 + 4.444j'
listOut =  eval(listIn)

print(listOut[0])
print(listOut[0].imag,listOut[0].real)

您最初的解析问题就是一个很好的例子,因为它强调了尽可能使用最简单、最高级别的解析工具的重要性。简单的高级工具包括一些基本的东西,如拆分、剥离和字符串索引。Regex可能被认为是一个中级工具,它当然是一个更复杂的工具。您选择的最低级工具是逐角色分析。永远不要这样做,除非你是迫于眼前的问题而被迫这样做的

以下是使用简单工具解析示例输入的一种方法:

# Helper function to take a string a return a complex number.
def s2complex(s):
    r, _, i = s.split()
    return complex(float(r), float(i[:-1]))

# Parse the input.
raw = '[1.111 + 2.222j, 3.333 + 4.444j]'
xs = raw[1:-1].split(', ')
nums = [s2complex(x) for x in xs]

# Check.
for n in nums:
    print(n)

相关问题 更多 >