Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

python - Sum lists of lists

Taking the following lists

matrix1 = [[1, 1], [2, 3]]
matrix2 = [[1, 1], [2, 3]]

How does return, without using additional libraries (such as pandas, numpy,...), the sum of the various lists of lists, in these case 2, as

[[2, 2], [4, 6]]

With the following

def addMatrix(m1, m2):

    if len(m1) == len(m2):
        return [x[0] + x[1] for x in zip(m1, m2)]
    else:
        raise ValueError("Given matrices are not the same size.")

It returns

>>> addMatrix(matrix1, matrix2)
[[1, 1, 1, 1], [2, 3, 2, 3]]

Which is not what one wants and would only work for lists, not lists of lists.

One has tried the following as well, but gives the same output as above

new = [] 

def add(m1, m2):
    for i, value in enumerate(m1):
        if len(m1) == len(m2):
            additional = m2[i]
            new.append(value + additional)
        else:
            raise ValueError("Given matrices are not the same size.")

One knows how to do it with numpy, but an approach without using any libraries is what one wants.

Here is a working solution with numpy

import numpy as np

matrix1_np = np.asarray(matrix1)
matrix2_np = np.asarray(matrix2)
add = matrix1_np + matrix2_np
add.tolist()
question from:https://stackoverflow.com/questions/65891008/sum-lists-of-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
[list(map(sum, zip(*i))) for i in zip(matrix1, matrix2)]

output

[[2, 2], [4, 6]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...