I would like to know how to do the summary of value contained in a matrix?I currently have this code for input of my matrix:
matrix = []
loop = True
while loop:
line = input()
if not line:
loop = False
values = line.split()
row = [int(value) for value in values]
matrix.append(row)
For example,the matrix [[1,2,3],[4,5,6]] would result 21,the summary of all the values.And im not quite sure on how to do that.
Thank you!
You can use the built-in sum()
function. As your matrix isn't flat, but a list of lists, you need to flatten it for sum()
:
sum(val for row in matrix for val in row)