问题
Assume I have a list of strings and I want to convert it to the numpy array. For example I have
A=A=['[1 2 3 4 5 6 7]','[8 9 10 11 12 13 14]']
print(A)
['[1 2 3 4 5 6 7]', '[8 9 10 11 12 13 14]']
I want my output to be like the following : a matrix of 2 by 7
[1 2 3 4 5 6 7;8 9 10 11 12 13 14]
What I have tried thus far is the following:
m=len(A)
M=[]
for ii in range(m):
temp=A[ii]
temp=temp.strip('[')
temp=temp.strip(']')
M.append(temp)
print(np.asarray(M))
however my output is the following:
['1 2 3 4 5 6 7' '8 9 10 11 12 13 14']
Can anyone help me to correctly remove the left and right brackets and convert the result to the matrix of floats.
回答1:
Just go the direct route. Remove the brackets, split on the spaces and convert to float before sending the result to numpy.array:
np.array([[float(i) for i in j[1:-1].split()] for j in A])
Test Code:
import numpy as np
A = ['[1 2 3 4 5 6 7]','[8 9 10 11 12 13 14]']
print(np.array([[float(i) for i in j[1:-1].split()] for j in A]))
Results:
[[ 1. 2. 3. 4. 5. 6. 7.]
[ 8. 9. 10. 11. 12. 13. 14.]]
来源:https://stackoverflow.com/questions/56642038/convert-list-of-strings-to-numpy-array-of-floats