python - 在python中创建对象矩阵
问题描述
我需要在 python 中创建一个对象矩阵。我找到了各种语言的其他解决方案,但是在 python 中找不到可靠且有效的方法来执行此操作。
给定班级
class Cell():
def __init__(self):
self.value = none
self.attribute1 = False
self.attribute2 = False
我想尽可能有效地制作多个“单元格”的矩阵。由于矩阵的大小将大于 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()]]
numpy.array
如果您愿意,也可以将它们包裹起来
NumPy 数组已满
您还可以使用内置的 numPyfull
方法并生成一个n
由m
您的值填充的 numpy 数组:
mat = numpy.full((num_rows, num_cols), Cell())
文档可以在这里找到
推荐阅读
- ios - 选择同一项目时,SwiftUI 三列导航布局未关闭
- css - 在播放前从嵌入的 youtube iframe 中的缩略图中隐藏“在 Youtube 上观看”
- sql-server - 将 Powershell 变量传递到 SQL INSERT
- css-selectors - 如何在类内的href中选择img?
- c++ - 如何在 C++ 中获取动态数组索引大小
- c# - 我无法从 wwwroot/images 中的文件夹加载图片
- c# - OwnedEntity 作为 PrimaryKey EF Core 5
- google-cloud-platform - 限制对公共 Cloud Run 端点的访问
- javascript - 未创建不和谐角色
- python - 如何在 Tkinter 中将目录中的图像显示为标签?