```
#import csv
# read matrix from file
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

asked March 20th 20 at 11:28

3 answers

answered on

Solution

so

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.

```
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.

answered on

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)

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)
```

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

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:

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:

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)
```

commented on March 20th 20 at 11:38 answered on March 20th 20 at 11:34

Don't invent a Bicycle

https://docs.scipy.org/doc/numpy/reference/generat...

https://docs.scipy.org/doc/numpy/reference/generat...

thank you. although I didn't need the amount in the matrix, but the link is useful commented on March 20th 20 at 11:37

Find more questions by tags Python

`print(sum(map(sum, matrix)))`

- geraldine_Ratke commented on March 20th 20 at 11:33how 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:

- Valerie commented on March 20th 20 at 11:39

- geraldine_Ratke commented on March 20th 20 at 11:42

here's a cycle satisfies my request beauty:

the matrix is displayed, just like in the file - Valerie commented on March 20th 20 at 11:45