I would like to write this:
x = 'something_{}'.format(1)
exec('{} = {}'.format(x,np.zeros((2,2))))
Problem: I get SyntaxError: invalid syntax
and I don't know how to solve it.
Someone has an idea?
I would like to write this:
x = 'something_{}'.format(1)
exec('{} = {}'.format(x,np.zeros((2,2))))
Problem: I get SyntaxError: invalid syntax
and I don't know how to solve it.
Someone has an idea?
String representation of numpy array is not a valid Python literal, therefore it cannot be eval
ed.
z = np.zeros((2,2))
str(z) # [[ 0. 0.]\n [ 0. 0.]] <-- invalid literal
Technically what you want may be achieved by using repr of object (but in general case it also won't work, e.g. when size of matrix is huge):
import numpy as np
x = 'something_{}'.format(1)
exec('{} = np.{!r}'.format(x, np.zeros((2,2))))
But what you really want to do is dynamic variable name, and that's a duplicate.