问题
I have this list of solutions from Sympy solver:
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?
回答1:
You can call the builtin function complex on each element, and then pass the result to 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:
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:
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
:
In [29]: np.fromiter(z, dtype=complex)
Out[29]: array([ 1.+3.5j, 2.+3.j , 4.-5.j ])
来源:https://stackoverflow.com/questions/41545831/convert-from-sympy-core-add-add-to-numpy-complex-number