Phillipe Pépin
Phillipe Pépin

Reputation: 47

Inserting elements at a specific index python

I'm trying to insert a list of number into a list of list. I've simplified the code just as an example because the actual thing is fairly long. Basically i have two list and the end result i want is as follows:

C = [
[1,1,x],
[2,1,x],
[3,1,x],
[1,2,x],
[2,2,x],
[3,2,x],
[1,3,x],
[2,3,x],
[3,3,x],
]

You can think of this as a matrix of nxn dimensions, but the list has to be like this. Basically my problem is that i can't figure out how to insert the first list into index 0 and 1 like in the matrix above. The second list is just the x's at index 3 which i can work my way around.

Here is what i have so far, any help would be appreciated. Thanks a lot!!

set_I = [1,2,3]


set_J = [x,x,x,x,x,x,x,x,x]


C = []
for i in range(len(set_I)*len(set_I)):
    C.append([])

for liste in C:
    liste.insert(0,0)
    liste.insert(1,0)
    liste.insert(2,0)

Upvotes: 1

Views: 53

Answers (3)

J Karthik Reddy
J Karthik Reddy

Reputation: 46

I guess if you are looking for that problem, then I guess you must use this code set_I = [1,2,3]

   set_J = ['x','x','x','x','x','x','x','x','x']
   
   
   C = []
   for i in range(len(set_I)*len(set_I)):
       C.append([])
   
   for i in range(len(set_I)):
       for j in range(len(set_I)):
           C[3*i+j].append(j+1)
           C[3*i+j].append(i+1)
           C[3*i+j].append(set_J[3*i+j])

Upvotes: 0

Finomnis
Finomnis

Reputation: 22581

Super wild guess:

set_I = [1,2,3]

set_J = [20,21,22,23,24,25,26,27,28]

C = []
for i in range(len(set_I)):
    for j in range(len(set_I)):
        C.append([set_I[j], set_I[i], set_J[3*i+j]])

print(C)

Result:

[
   [1, 1, 20],
   [2, 1, 21],
   [3, 1, 22],
   [1, 2, 23],
   [2, 2, 24],
   [3, 2, 25],
   [1, 3, 26],
   [2, 3, 27],
   [3, 3, 28]
]

Upvotes: 1

Bobby Ocean
Bobby Ocean

Reputation: 3326

I am confused. If you want the product, then use it.product(), like:

set_I = [1,2,3]
set_J = [0,0,0,0,0,0,0,0,0] #Just putting zeros instead of x's. 

import itertools as it

[[a,b,c] for (a,b),c in zip(it.product(set_I,repeat=2),set_J)]

If you want to initialize an empty list of list, then simply multiply.

[[0]*3]*9

Upvotes: 0

Related Questions