我需要在 python 中创建一个对象矩阵。我已经找到了各种语言的其他解决方案,但是找不到可靠且有效的方法来在 python 中执行此操作。
给定类(class)
class Cell():
def __init__(self):
self.value = none
self.attribute1 = False
self.attribute2 = False
我想尽可能高效地制作多个“单元”的矩阵。由于矩阵的大小将大于 20 x 20,因此迭代方法将很有用。任何贡献都是有帮助的
最佳答案
更新正确性
numpy.full
答案将复制单个现有的 Cell()
,为您提供对一个对象的引用。此处使用列表理解:
row = [[Cell() for _ in range(num_cols)] for _ in range(num_rows)]
旧答案
如果您已经定义了对象,列表推导式可以在这里提供帮助:
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 数组已满
您还可以使用内置的 numPy full
方法,并生成一个 n
by m
numpy 数组,其中填充了您的值:
mat = numpy.full((num_rows, num_cols), Cell())
可以找到文档 here
关于python - 在Python中创建对象矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53191910/