如何将字符串 '1.000,0.001' 转换为复数 (1+0.001j)?

How to convert the string '1.000,0.001' to the complex number (1+0.001j)?

我能想到的最好的是

s = '1.000,0.001'
z = [float(w) for w in s.split(',')]
x = complex(z[0],z[1])

有没有更短、更干净、更好的方法?

我想你可以做得稍微短一点

real, imag = s.split(',')
x = complex(float(real), float(imag))

不涉及列表理解。

你有的很好。我可以建议的唯一改进是使用

complex(*z)

如果要单行的话:

>>> complex(*map(float, s.split(',')))
(1+0.001j)

有一种更简洁的方法,但实际上并没有更简洁,当然也没有更清晰。

x = complex(*[float(w) for w in '1.000,.001'.split(',')])

如果您相信这些数据没有危险,或者希望将其用于代码高尔夫:

>>> eval('complex(%s)' % s)
(1+0.001j)