Is there a way to simplify this function using a one-line comprehension in python?

Question:

simple question, as the title implies. I was hoping to use the zip function but can’t get it to work for some reason.

def tuple_sum(A, B):
out = []
for a,b in [x for x in zip(A,B)]:
    out1 = []
    for a1, b1 in zip(a, b):
        out1.append(a1+b1)
    out.append(out1)
return out
Asked By: Reuben

||

Answers:

Maybe something like this?

A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
s = [[a1 + b1 for a1, b1 in zip(a, b)] for a, b in zip(A, B)]
print(s)  # [[6, 8], [10, 12]]
Answered By: tkburis
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.