在 Python 中通过列表理解(和 zip)将矩阵元素添加为嵌套列表

Adding matrix elements as the nested lists by list comprehension (and zip) in Python

我尝试通过以下方式继续添加 2 个矩阵的矩阵元素 使用列表理解和 zip,因为我认为执行起来非常简单。不幸的是,我曾尝试以众所周知的“过于聪明”的方式来做到这一点,但我失败了。我仍然不明白我在哪里犯了错误,在复杂的理解结构中锻炼我的大脑是我想念的训练。

我尝试以嵌套列表的形式执行 2 个矩阵相加的代码:

def main() 中的示例输入:

看起来这个片段产生了重大错误:

new_matrix[index] = zip(row, other[index])
IndexError: list assignment index out of range
class Matrix:

    def __init__(self, matrix):
        self.matrix = matrix

    def add(self,number_of_rows, number_of_columns, other):
        new_matrix = [[] * len(self.matrix)]
        if len(self.matrix) == len(other) and len(self.matrix[0]) == len(other[0]):
            for index, row in enumerate(self.matrix):
                new_matrix[index] = zip(row, other[index])
            return [[x + y for (x, y) in new_matrix[index]] for index in range(0, len(new_matrix))]

def main():
    matrix1 = Matrix([[1,2,3], [2,3,4],[4,5,6]])
    matrix2 = matrix1.add([[1,2,3],[2,3,4],[4,5,6]])
    print(matrix2)



if __name__ == '__main__':
    main()

问题是new_matrix = [[] * len(self.matrix)]

我假设您期望 [[] * 3] 会给出: [[], [], []] 但事实并非如此。

[]*N 只是 [] 对于每个 N

所以你的 new_matrix 是只有一个元素的列表,它是 [] 并且当你尝试分配给 new_matrix[1] 时你会得到你的错误。

改为执行: new_matrix = [[]] * len(self.matrix)

  • 我还没有测试你的其余代码

更新 - 用我的修复检查了你的例子,它正在工作