Domanda

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!

È stato utile?

Soluzione

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)

Altri suggerimenti

You can use list comprehension:

matrix = [[1, 2, 3], [4, 5, 6]]
sums = sum(y for x in matrix for y in x)
print sums

This runs as:

>>> matrix = [[1, 2, 3], [4, 5, 6]]
>>> sums = sum(y for x in matrix for y in x)
>>> print sums
21
>>> 

Or you could use a basic for loop:

matrix = [[1, 2, 3], [4, 5, 6]]
sums = 0
for sub in matrix:
    for value in sub:
        sums+=value

print sums

This runs as:

>>> matrix = [[1, 2, 3], [4, 5, 6]]
>>> sums = 0
>>> for sub in matrix:
...     for value in sub:
...         sums+=value
... 
>>> print sums
21
>>> 

List comprehension is the same as the double for loops, only in one line:

Explanation of the following:

sums = sum(y for x in matrix for y in x)

Let's start at the beginning:

We use the builtin function sum() to calculate all the values in the list:

>>> sum([1, 2, 3, 4]) #Should be 10
10
>>> 

However, sum() only works with flattened lists:

>>> sum([[1, 2], [3, 4]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> 

Thus, we need to flatten it with double for loops:

sum(y for x in matrix for y in x)

The for x in matrix is basically taking every value of matrix, essentially [1, 2, 3] and [4, 5, 6] in this case. The for y in x is assigning y to every value of x, [1, 2, 3, 4, 5, 6]. This is our flattened out list. Then we call sum(), and everything works like magic!

here is a function that will do that

M = [[1,2,3],[4,5,6]]

def matrixSummary( M ):
    rowSums=[]
    for row in M:
        rowSums.append( sum( row ))
    return sum( rowSums )
matrixSummary( M )
// Result: 21 //

looks like CoDEmanX has a nice list comprehension version

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top