Zeir
Zeir

Reputation: 289

conditional sum over a range python

I have created X as folowing

num_locations = 2
X= [ ]
for n in range(num_locations):
X.append([0 for j in range(num_locations)])

Now I want to sum these X[n][m] values for the case n != m . Such that the result should be like

X[0][1]+X[1][0]

Is there a way to do that with the sum formulation ?

X[n][m] for n in range(num_locations)for m in range(num_locations))

Upvotes: 2

Views: 1609

Answers (3)

miradulo
miradulo

Reputation: 29720

This is effectively taking the sum of the non-diagonal elements of your 2D array. One option using Numpy could simply be to subtract the sum of the main diagonal (np.trace) from the sum of the entire array.

num_locations = 2
X= [[1,2],[2,1]]

import numpy as np
s = np.sum(X) - np.trace(X)
print(s)

Outputs:

4

Upvotes: 2

Neo
Neo

Reputation: 3786

This should work

sum([sum(row) - (row[i] if len(row) < i else 0) for i,row in enumerate(X)])

It runs over every row in the 2d array, and sums it, then take out the i cell (if exists) so it won't get into sum

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78554

You can simply use enumerate

>>> sum(o for i, a in enumerate(X) for j, o in enumerate(a) if i!=j)
0

Where i and j are row (1st dim) and column (2nd dim) indices respectively

Upvotes: 2

Related Questions