我想创建一个具有已知行数(3)的列表或矩阵,但是对于每一行,元素数将有所不同。 因此可能看起来像这样:
[[4, 6, 8],
[1, 2, 3, 4],
[0, 2, 3, 4, 8]]
每行将具有最多已知的elements(8)。
到目前为止,我已经尝试了以下方法:
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]
我想要这个是因为我想为range(3)中的每个j都有一个列表,可以在该列表上进行for循环并向我的ILP添加约束。
任何帮助将不胜感激!
答案 0 :(得分:0)
以下是代码外观的示例:
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)