首页 > 解决方案 > 在python中创建对象矩阵

问题描述

我需要在 python 中创建一个对象矩阵。我找到了各种语言的其他解决方案,但是在 python 中找不到可靠且有效的方法来执行此操作。

给定班级

class Cell():
    def __init__(self):
        self.value = none 
        self.attribute1 = False
        self.attribute2 = False

我想尽可能有效地制作多个“单元格”的矩阵。由于矩阵的大小将大于 20 x 20,因此迭代方法将很有用。任何贡献都是有帮助的

标签: pythonoopobjectmatrix

解决方案


如果您已经定义了对象,列表推导可以在这里提供帮助:

num_rows = 5
num_cols = 6

row = [Cell() for i in range(num_cols)]
# The original way doesn't behave exactly right, this avoids 
# deep nesting of the array. Also adding list(row) to create
# a new object rather than carrying references to row to all rows
mat = [list(row) for i in range(num_rows)]

#[[Cell(), Cell(), Cell()...], [...], ..., [Cell(), ..., Cell()]]

numpy.array如果您愿意,也可以将它们包裹起来

NumPy 数组已满

您还可以使用内置的 numPyfull方法并生成一个nm您的值填充的 numpy 数组:

mat = numpy.full((num_rows, num_cols), Cell())

文档可以在这里找到


推荐阅读