Reputation: 1993
I'm trying to replace something like this code, for a vectorized efficient operation using numpy.
counter = 0
idxs = [1, 3]
lists = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
for l in lists:
for idx in idxs:
counter += l[idx]
Upvotes: 0
Views: 459
Reputation: 42748
Just sum the array:
idxs = [1, 3]
lists = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
ary = np.array(lists)
counter = ary[:,idxs].sum()
Upvotes: 1