Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. # Our list of lists.
  2. matrix_1 = [[1,1,1], [2,2,2], [3,3,3]]
  3. matrix_2 = [[4,4,4], [5,5,5], [6,6,6]]
  4.  
  5. # Matrix addition with for loop.
  6. # Assuming that the matrices are of the same dimensions
  7. matrix_sum = []
  8. for row in range(len(matrix_1)):
  9. matrix_sum.append([])
  10. for column in range(len(matrix[0])):
  11. matrix_sum[row].append(matrix_1[row][column] + matrix_2[row][column])
  12.  
  13. # Rewrite using list comprehension only for inner lists.
  14. matrix_sum = []
  15. for row in range(len(matrix_1)):
  16. matrix_sum.append([matrix_1[row][column] + matrix_2[row][column] for column in range(len(matrix[0]))])
  17.  
  18. # Rewrite using nested list comprehension.
  19. matrix_sum = [[matrix_1[row][column] + matrix_2[row][column] for column in range(len(matrix[0]))]
  20. for row in range(len(matrix_1))]
  21.  
  22. print(matrix_sum) # Output: [[5, 5, 5], [7, 7, 7], [9, 9, 9]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement