我convert a string representation of a list to a list可ast.literal_eval
。是否存在numpy数组的等价物?
x = arange(4)
xs = str(x)
xs
'[0 1 2 3]'
# how do I convert xs back to an array
使用ast.literal_eval(xs)
会引发SyntaxError
。如果需要,我可以进行字符串解析,但我认为可能有更好的解决方案。
答案 0 :(得分:10)
从这开始:
x = arange(4)
xs = str(x)
xs
'[0 1 2 3]'
试试这个:
import re, ast
xs = re.sub('\s+', ',', xs)
a = np.array(ast.literal_eval(xs))
a
array([0, 1, 2, 3])
答案 1 :(得分:2)
对于1D数组Numpy has a function called fromstring
,所以无需额外的库就可以非常高效地完成。
简单地说,您可以像这样解析字符串:
FXMLLoader loader = new FXMLLoader(View.class.getResource("AdminLayout.fxml"));
Parent p = loader.load();
对于nD数组,可以使用s = '[0 1 2 3]'
a = np.fromstring(s[1:-1], dtype=np.int, sep=' ')
print(a) # [0 1 2 3]
删除括号,使用.replace()
重塑为所需的形状,或使用Merlin的解决方案。