I cannot figure out how to add integers together in two matrices using the zip()
function. Here is what I have:
matrix_a = [[3,6],[4,5]]
matrix_b = [[5,8],[6,7]]
I need to print out (using zip()
):
[[8,14],[10,12]]
The following list comprehension will do the trick:
>>> [[x + y for x, y in zip(a, b)] for a, b in zip(matrix_a, matrix_b)]
[[8, 14], [10, 2]]
If you want the version that uses loops:
result = []
for a, b in zip(matrix_a, matrix_b):
current_list = []
for x, y in zip(a, b):
current_list.append(x + y)
result.append(current_list)
>>> result
[[8, 14], [10, 2]]
However, I definitely like more the comprehension version it is easier to read.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.