Home > database >  how can a write a 2-d array without any imports?
how can a write a 2-d array without any imports?

Time:01-10

anyone know how to write a 2d array? The result:

[[0,1,0]

[0,2,0]

[0,3,0]]

And with no imports OR ANY LIBERARIES'

a=[]
for y in range (3):
    row=[]
    for x in range (3):
        row.append(0)
        a.append(row)

i've come up this far

the answer should contain these codes you can add and edit but you can't remove

CodePudding user response:

Naively, you could write this 2D array as a literal:

arr = [[0,1,0], [0,2,0], [0,3,0]]

but I guess this isn't what you meant. You could also use list comprehensions to build it from a range:

arr = [[0, i   1, 0] for i in range(3)]

CodePudding user response:

As mentioned. The answer should contain these codes you can add and edit but you can't remove

Code:

a=[]
for i in range(1,4):
    tmp=[]
    for j in range(3):
        if j!=1:
            tmp.append(0)
        elif j==1:
            tmp.append(i)
    a.append(tmp)
print(a)

Output:

[[0, 1, 0], [0, 2, 0], [0, 3, 0]]
  • Related