0

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! :)

1
  • Your first suggestion is the shortest you can make it. If it's unreadable, extract a square_shape(length) function, and use np.zeros(square_shape(len(l))) Commented Feb 22, 2019 at 18:03

2 Answers 2

1

You can try:

shp = int(np.sqrt(len(l))
a = np.zeros((shp, shp))
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

This is what i tried in the first attempt. But it is so bad readable. And so many variables for such a small task, I also do not like^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.