Max16hr
Max16hr

Reputation: 468

Numpy: Transform list into square array

I have a list t with a square number of elements, e.g. 16, 25, 400. Now want to create a numpy array a full of zeros with the same size but in a square shape, e.g. 4x4, 5x5, 20x20.

I found a solution:

a = np.zeros(2 * (int(np.sqrt(len(t))),))

or

a = np.zeros(len(t)).reshape(int(np.sqrt(len(t))), int(np.sqrt(len(t))))

It is working, but it is very ugly and I am sure there must be a better way to do this. Something like a = np.zeros(t, 2). Any idea for that?

Thank you! :)

Upvotes: 0

Views: 1004

Answers (2)

liamhawkins
liamhawkins

Reputation: 1381

You can clean it up like so:

size = len(l)
sqrt = int(np.sqrt(size))
a = np.zeros((sqrt, sqrt))

Any time you are writing the same fragment of code multiple times, it is good to replace with a variable, function etc.

Upvotes: 1

sacuL
sacuL

Reputation: 51395

You can try:

shp = int(np.sqrt(len(l))
a = np.zeros((shp, shp))

Upvotes: 1

Related Questions