制作二维列表/矩阵,每个列表/矩阵具有不同的列数

2024-04-25 06:22:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个列表或矩阵,有一个已知的行数(3),但每行的元素数量将是不同的。 所以它看起来像这样:

[[4, 6, 8],
[1, 2, 3, 4],
[0, 2, 3, 4, 8]]

每行将有一个已知的最大元素数(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]

我之所以这样做是因为我想为范围(3)中的每个j创建一个列表,在这个列表上我可以执行for循环并向ILP添加约束。你知道吗

任何帮助都将不胜感激!你知道吗


Tags: or方法in元素列表for数量if
1条回答
网友
1楼 · 发布于 2024-04-25 06:22:11

下面是代码的示例:

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)

相关问题 更多 >