简体   繁体   中英

Add integers of two lists of lists together

I am trying to write a function that accepts two lists-of-lists of numbers and returns one list-of-lists with each of the corresponding numbers in the two given lists-of-lists added together. Without using any third-party libraries (without using pandas for example).

It should work something like this:

>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> add(matrix1, matrix2)
[[3, -3], [-3, 3]]

My current code:

list_3 = []


# Add function

def add(*args):
    for arg in args:
        for i in range(0, len(args)):
                list_3.append(arg[i - 1] + arg[i - 1] + arg[i - 1])
                print(f"Result: {list_3}")

My code does not work. Help would be appreciated.

This is simple to do with a couple of nested comprehensions using zip :

>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> [[a + b for a, b in zip(x, y)] for x, y in zip(matrix1, matrix2)]
[[3, -3], [-3, 3]]

or maybe using map and sum to build the inner lists:

>>> [list(map(sum, zip(x, y))) for x, y in zip(matrix1, matrix2)]
[[3, -3], [-3, 3]]

You can iterate through the arguments, then iterate through the items of each arguments.

def add(*args):
    list_tmp = []
    for arg in args:
        for item in arg:
            list_tmp.append(item)
    return list_tmp

I also advise you to store the items in a local variable ( list_tmp ) and to return it: you can avoid a global variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM