# How to calculate the sum of the numbers in the matrix?

``````#import csv

with open('in.txt') as f:
matrix = [list(map(int, row.split())) for row in f.readlines()]

print(matrix)

s = sum(matrix)
print(s)

# save the matrix in another file
with open('output.txt', 'w') as f:
for row in matrix:
f.write(' '.join(map(str, row)) + '\n')`````` for example, this code works
chars = [1,2,3,4,5]
s = sum(chars) # 15
print(s)
and for two-dimensional lists, no
March 20th 20 at 11:28
March 20th 20 at 11:30
Solution
so
``````import functools

matrix = [[]]

result = functools.reduce(lambda a,x: a + sum(x), matrix, 0)
print(result)``````

but if the matrix as a two-dimensional array (even if empty), if the matrix is simply a list, there is an error. How to make more competently, maybe now experienced pythonista prompt.
`print(sum(map(sum, matrix)))` - geraldine_Ratke commented on March 20th 20 at 11:33
@Chelsea.Barrows99, that's right! and compact) - Valerie commented on March 20th 20 at 11:36
@Chelsea.Barrows99,
how to remove excessive brackets in the output?
how to transfer each row of the matrix on a new line in the output?

I'm a little nice: ``````with open('in.txt') as f:
matrix = [list(map(int, row.split())) for row in f.readlines()]

print(matrix)

print(sum(map(sum, matrix)))``````
- Valerie commented on March 20th 20 at 11:39
I have a little not nice
it should be
how to transfer each row of the matrix on a new line in the output?
``````from pprint import pprint

pprint([[1, 0, 0], [0, 1, 0], [0, 0, 1]], width=20)``````
- geraldine_Ratke commented on March 20th 20 at 11:42
@Chelsea.Barrows99,

here's a cycle satisfies my request beauty:

``````#print(*matrix) is much more beautiful display, see loop below
for i in matrix:
for j in i:
print(j,end=' ')
print()``````

the matrix is displayed, just like in the file - Valerie commented on March 20th 20 at 11:45
March 20th 20 at 11:32
Solution
with open('in.txt') as f:
matrix = [list(map(int, row.split())) for row in f.readlines()]

print(matrix)
for m in matrix:
s = sum(m)
print(s)
``````s = 0
for m in matrix:
s += sum(m)``````
- kyleigh3 commented on March 20th 20 at 11:35
@Carmela76 your summation gives the result 4,
not a plus latest third row of the matrix
@ted.Emard83 your summation gives the result 8 is true!

the output of the Maritsa on the screen
`print(matrix)`
gives this result: how to make the matrix was not written in one line, but that was postponed after every few items on a new line, as it is written in the file? and how to make. to not highlight brackets derived from the matrix?

code:
``````with open('in.txt') as f:
matrix = [list(map(int, row.split())) for row in f.readlines()]

s = 0
for m in matrix:
s += sum(m)
print(s)

print(matrix)``````
- Valerie commented on March 20th 20 at 11:38
March 20th 20 at 11:34
thank you. although I didn't need the amount in the matrix, but the link is useful - Marcel.Marks commented on March 20th 20 at 11:37

Find more questions by tags Python