从sympy.core.add.Add转换为numpy复数

时间:2022-04-29 20:19:47

I have this list of solutions from Sympy solver:

我有Sympy解算器的这个解决方案列表:

In [49]: sol
Out[49]: 
[-1.20258344291917 - 0.e-23*I,
 -0.835217129314554 + 0.e-23*I,
 0.497800572233726 - 0.e-21*I]

In [50]: type(sol)
Out[50]: list

In [51]: type(sol[0])
Out[51]: sympy.core.add.Add

How can I convert this list to a numpy object with cells which are normal complex value?

如何将此列表转换为具有正常复杂值的单元格的numpy对象?

1 个解决方案

#1


6  

You can call the builtin function complex on each element, and then pass the result to np.array().

您可以在每个元素上调用内置函数complex,然后将结果传递给np.array()。

For example,

例如,

In [22]: z
Out[22]: [1 + 3.5*I, 2 + 3*I, 4 - 5*I]

In [23]: type(z)
Out[23]: list

In [24]: [type(item) for item in z]
Out[24]: [sympy.core.add.Add, sympy.core.add.Add, sympy.core.add.Add]

Use a list comprehension and the builtin function complex to create a list of python complex values:

使用列表推导和内置函数complex来创建python复合值列表:

In [25]: [complex(item) for item in z]
Out[25]: [(1+3.5j), (2+3j), (4-5j)]

Use that same expression as the argument to numpy.array to create a complex numpy array:

使用与numpy.array的参数相同的表达式来创建复杂的numpy数组:

In [26]: import numpy as np

In [27]: np.array([complex(item) for item in z])
Out[27]: array([ 1.+3.5j,  2.+3.j ,  4.-5.j ])

Alternatively, you can use numpy.fromiter:

或者,您可以使用numpy.fromiter:

In [29]: np.fromiter(z, dtype=complex)
Out[29]: array([ 1.+3.5j,  2.+3.j ,  4.-5.j ])

#1


6  

You can call the builtin function complex on each element, and then pass the result to np.array().

您可以在每个元素上调用内置函数complex,然后将结果传递给np.array()。

For example,

例如,

In [22]: z
Out[22]: [1 + 3.5*I, 2 + 3*I, 4 - 5*I]

In [23]: type(z)
Out[23]: list

In [24]: [type(item) for item in z]
Out[24]: [sympy.core.add.Add, sympy.core.add.Add, sympy.core.add.Add]

Use a list comprehension and the builtin function complex to create a list of python complex values:

使用列表推导和内置函数complex来创建python复合值列表:

In [25]: [complex(item) for item in z]
Out[25]: [(1+3.5j), (2+3j), (4-5j)]

Use that same expression as the argument to numpy.array to create a complex numpy array:

使用与numpy.array的参数相同的表达式来创建复杂的numpy数组:

In [26]: import numpy as np

In [27]: np.array([complex(item) for item in z])
Out[27]: array([ 1.+3.5j,  2.+3.j ,  4.-5.j ])

Alternatively, you can use numpy.fromiter:

或者,您可以使用numpy.fromiter:

In [29]: np.fromiter(z, dtype=complex)
Out[29]: array([ 1.+3.5j,  2.+3.j ,  4.-5.j ])