python - 在Python中创建对象矩阵

标签 python oop object matrix

我需要在 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/

相关文章:

java - 当实例在另一个文件中声明时访问 GUI 文件中的实例

c# - 将属性从基类向下移动到子类

c# - 如何将多个视觉元素作为一项任务批量打印?

javascript - 如何在 Javascript 中同时遍历对象的属性?

python - 如何在plotly3(不是plotly4)中并排绘制表格和散点图

Python.el 和 Python 模式 : Documentation & Features

C#:AmbigeousMatchException:发现不明确的匹配

javascript - 使用一个键的值数组过滤多个 javascript 对象

python - 将 DataFrame 字符串列拆分为 N 个拆分

python - 使用 scikit-learn 加载文本数据时出现问题?