Making a 2 dimensional list/matrix with different number of columns for each row
Making a 2 dimensional list/matrix with different number of columns for each row
I would like to make a list or matrix that has a known number of rows(3), but for each row the number of elements will be different.
So it could look something like this:
[[4, 6, 8],
[1, 2, 3, 4],
[0, 2, 3, 4, 8]]
Each row will have a known maximum of elements(8).
So far I have tried the following:
Sets1=np.zeros((3,8))
for j in range(3):
Sets1[0,:]=[i for i, x in enumerate(K[:-1]) if B[x,j]==1 or B[x+1,j]==1]
I want this because I want to have a list for each j in range(3) over which I can do a for loop and add constraints to my ILP.
Any help will be greatly appreciated!
You shouldn't call that a matrix because matrix is a rectangular array of numbers. It's just a 2D array.
– Kasramvd
Jun 29 at 8:36
Edit: Never mind I have figured it out.. I just wanted a list of lists. A got by creating an empty list and then just appending each list with the list I needed. Thanks though!!
– Tine
Jun 29 at 8:37
1 Answer
1
Here is a sample of what your code should look like:
from random import *
myMatrix = [
,
,
]
elementsNums = [1, 2, 3, 4, 5, 6, 7, 8] # possible length of each list in the matrix
elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # random values in each list in the matrix
def addElements(Num, List, Matrix):
count = 0
a = choice(Num) #length of first list in matrix
Num.remove(a) # removing to prevent same length lists in matrix
b = choice(Num) # length of second list in matrix
Num.remove(b)
c = choice(Num) # length of third list in matrix
nums = [a, b, c]
for x in nums: # iterating through each list (a, b, c)
for i in range(x): # placing x number of values in each list
Matrix[count].append(choice(List)) # adding the values to the list
count += 1 # moving to the next list in the matrix
addElements(elementsNums, elements, myMatrix)
print(myMatrix)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Final expected output for the given sample?
– Divakar
Jun 29 at 8:35