-1

I have some matrix containing integers:

matrix = [[85, 61, 48, 100, 96],
 [23, 72, 13, 45, 36],
 [97, 80, 65, 84, 46],
 [80, 59, 76, 61, 99]]

and a matrix containing:

index = [[-1, 0, 0, -1, -1],
 [0, -1, 0, -1, -1],
 [-1, 0, -1, -1, 0],
 [-1, 0, -1, 0, -1]]

I want to sum all the elements of matrix, where the element in index is equal to -1, but I can't use any package. The expected output should be 935.

Thanks in advance.

2 Answers 2

1

Use a generator expression:

res = sum(v for ii, val in zip(index, matrix) for i, v in zip(ii, val) if i == -1)
print(res)

Output

935

As an alternative:

res = 0
for ii, val in zip(index, matrix):
    for i, v in zip(ii, val):
        if i == -1:
            res += v
0

You could use the itertools to flatten the matrix and zip it along the indices::

import itertools as it
sum([v for (i, v) in zip(it.chain.from_iterable(index), it.chain.from_iterable(matrix)) if i == -1])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.