Multidimensional array

Asked

Viewed 115 times

0

I am trying to create a multidimensional array. I first intended to place all the first elements with value 2 so I did:

l=4
x=6
TSup=[ [ 2 for i in range(l) ] for j in range(x) ]
print TSup

and I got what I expected:

[[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]]

Now I want to change the code so that the first value is the position of a Test list, that is, I wanted the first element to be 290, the 2º 293, the 3º 291 and the 4º 294, for that I changed as follows:

Test=[290,293,291,294]
l=4
x=6
for a in range(len(Test)):

    TSup=[ [ Test[a] for i in range(l) ] for j in range(x) ]

print (TSup)

but does not give the expected, gives only the value for the last iteration, 4th position:

[[294, 294, 294, 294], [294, 294, 294, 294], [294, 294, 294, 294], [294, 294, 294, 294], [294, 294, 294, 294], [294, 294, 294, 294]] 

and I wanted to:

[[290, 293, 291, 294],[290, 293, 291, 294],[290, 293, 291, 294],[290, 293, 291, 294],[290, 293, 291, 294],[290, 293, 291, 294]]

If anyone can help me, I’d really appreciate it!

3 answers

1

The operator * just for that:

n = 6
final = [[290, 293, 291, 294]]*n
  • What’s this operation called? Does it have a name? I wouldn’t do that

  • Check out this link: https://docs.python.org/3/faq/programming.html#Faq-multidimensional-list

  • 1

    Very good, I didn’t know

0

Do it like this:

for a in range(len(Test)):
    Tsup = [ [Test[i] for i in range(l)] for j in range(x) ]

or just like that:

Tsup = [ [Test[i] for i in range(l)] for j in range(x) ]

0

We have to create 6 matching test lists within a parent list':

test = [290,293,291,294]
final = [[i for i in test] for i in range(6)]
print(final) # [[290, 293, 291, 294], [290, 293, 291, 294], [290, 293, 291, 294], [290, 293, 291, 294], [290, 293, 291, 294], [290, 293, 291, 294]]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.