If we print a numpy array, which actually use str()
, we will find it almost irreversible.
In [5]:
l=arange(16).reshape(4,4)
print('l is printed as:\n', l)
Use print()
will fallback to str()
, so str()
is not the correct way.
repr()
.tolist()
In [77]:
print('Array Form:\n', repr(l))
print('List form:\n', l.tolist())
# Recover your fault
If you really need to convert the array string separated by spaces into python, here is a remedy str2array()
:
In [21]:
import re
import ast
def array2str(arr, precision=None):
s=array_str(arr, precision=precision)
return s.replace('\n', ',')
def str2array(s):
# Remove space after [
s=re.sub('\[ +', '[', s.strip())
# Replace commas and spaces
s=re.sub('[,\s]+', ', ', s)
return array(ast.literal_eval(s))
In [20]:
str2array(array2str(sqrt(l), 3))
Out[20]:
Comments
comments powered by Disqus