Add two matrices in python

前端 未结 4 1446
独厮守ぢ
独厮守ぢ 2020-12-17 15:45

I\'m trying to write a function that adds two matrices to pass the following doctests:

  >>> a = [[1, 2], [3, 4]]
  >>> b = [[2, 2], [2, 2]         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 16:23

    from itertools import izip
    
    def add_matrices(c, d):
        return [[a+b for a, b in izip(row1, row2)] for row1, row2 in izip(c, d)]
    

    But as said above, there is no need to reinvent the wheel, just use numpy, which is likely to be faster and more flexible.

提交回复
热议问题