Osc*_*son 1 python oop object matrix
我需要在python中制作一个对象矩阵。我已经找到了各种语言的其他解决方案,但是在 python 中找不到可靠且有效的方法。
鉴于班级
class Cell():
def __init__(self):
self.value = none
self.attribute1 = False
self.attribute2 = False
Run Code Online (Sandbox Code Playgroud)
我想尽可能有效地制作多个“单元格”的矩阵。由于矩阵的大小将大于 20 x 20,因此迭代方法会很有用。任何贡献都是有帮助的
如果您已经定义了对象,列表推导式可以在这里提供帮助:
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()]]
Run Code Online (Sandbox Code Playgroud)
numpy.array如果你愿意,你也可以把它们包起来
您还可以使用full内置的 numPy方法并生成一个用您的值填充的nby mnumpy 数组:
mat = numpy.full((num_rows, num_cols), Cell())
Run Code Online (Sandbox Code Playgroud)
文档可以在这里找到