python字符串变为数组_Python:将应该是数组的字符串转换回数组

罕见的用途eval():s = '[[[0,0,0],[0,0,0],[0,0,0]],[[1,1,1],[1,1,1],[1,1,1]],[[2,2,2],[2,2,2],[2,2,2]]]'

x = eval(s)

print(x) #[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[2, 2, 2], [2, 2, 2], [2, 2, 2]]]

编辑:正如所指出的那样,eval不足以满足您的要求。我最终得到的工作是建立在json和numpy之上s = '''[[[ nan nan nan]\n [ nan nan\nnan]\n [ nan nan nan]]\n\n [[ 0.005506 0.005506\nnan]\n [ 0.006684 nan nan]\n [ 0.006684 nan\nnan]]\n\n [[ nan nan nan]\n [ nan nan\nnan]\n [ nan nan nan]]]'''

import numpy, json

x = numpy.array(json.loads(','.join(s.split()).replace('[,','[').replace('nan','NaN')))

print(x)

#array([[[ nan, nan, nan],

# [ nan, nan, nan],

# [ nan, nan, nan]],

# [[ 0.005506, 0.005506, nan],

# [ 0.006684, nan, nan],

# [ 0.006684, nan, nan]],

# [[ nan, nan, nan],

# [ nan, nan, nan],

# [ nan, nan, nan]]])

您可以轻松地更换numpy.array()使用pandas.DataFrame()。

你可能感兴趣的:(python字符串变为数组)