1

I have a array as [2, 3, 1, 3, 1]
I want to define a 2 dimensional array of all 0s according to [2, 3, 1, 3, 1] it will be something like

[ [0,0], [0,0,0], [0], [0,0,0], [0] ]

how to do it without hardcoding?

0

3 Answers 3

2

A simple comprehension will do:

array = [2, 3, 1, 3, 1]

zeroes = [[0] * x for x in array]
# [[0, 0], [0, 0, 0], [0], [0, 0, 0], [0]]
Sign up to request clarification or add additional context in comments.

Comments

2

you could do something like this :

[[0 for x in range(y)] for y in [2,3,1,3,1]]

2 Comments

While it is not clear form the invalid output, the OP does ask for a 2-dimensional array, not a 3-dimensional one.
This is pretty hard to see with his data structure : [ [0][0], [0][0][0], [0], [0][0][0], [0] ] I was thinking that meant : [[[0], [0]], [[0], [0], [0]], [[0]], [[0], [0], [0]], [[0]]]. I made the changes thanks
1

You could do it like this:-

c = [2, 3, 1, 3, 1]
RA = []
for v in c:
    RA.append([0 for _ in range(v)])
print(RA)

There's probably a more compact way of doing this but this should make it clear what you need to do

Comments

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.