[英]How to create a matrix of lists?
I need to create a matrix MxN where every element of the matrix is a list of integers.我需要创建一个矩阵 MxN,其中矩阵的每个元素都是一个整数列表。 I need a list so that I can append new elements as I go, therefore a 3D matrix would not work here.我需要一个列表,以便我可以随时添加新元素,因此 3D 矩阵在这里不起作用。 I'm not sure if what I need here would actually be a list of lists.我不确定我在这里需要的是否实际上是一个列表列表。
The following function creates a 2D matrix of empty lists:以下函数创建空列表的二维矩阵:
>>> def create(row,col):
... return [[[] for _ in range(col)] for _ in range(row)]
...
>>> L = create(2,3)
>>> L[1][2].extend([1,2,3]) # add multiple integers at a location
>>> for row in L:
... print(row)
...
[[], [], []]
[[], [], [1, 2, 3]]
>>> L[0][1].append(1) # add one more integer at a location
>>> for row in L:
... print(row)
...
[[], [1], []]
[[], [], [1, 2, 3]]
How it works:这个怎么运作:
[]
is a new instance of an empty list. []
是一个空列表的新实例。[[] for _ in range(col)]
uses a list comprehension to create a list of "col" empty lists. [[] for _ in range(col)]
使用列表理解来创建“col”空列表的列表。[[] for _ in range(col)] for _ in range(row)
create "row" new lists of "col" empty lists. [[] for _ in range(col)] for _ in range(row)
创建“col”空列表的“row”新列表。In numpy, you can create a matrix with dtype=object (instead of the usual int or float).在 numpy 中,您可以使用 dtype=object(而不是通常的 int 或 float)创建一个矩阵。 This can be used to store empty lists, to which you can then append.这可用于存储空列表,然后您可以附加到该列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.