-1

This does not answer my Question Calculate mean across dimension in a 2D array

import numpy as np

L1 = list()
L2 = []
L3 = [3,4,1,6,7,5]
L4 = [[2, 9, -5], [-1, 0, 4], [3, 1, 2]]

The goal is to add up the values in L4.

How do I iterate over this MD array? I tried

a = np.asarray(L4)
print(a)
for (x,y), value in np.ndenumerate(a):
  print(x,y)
software is fun
  • 7,286
  • 18
  • 71
  • 129
  • `sum(sum(lst) for lst in L4)`? or `np.array(L4).ravel().sum()`? – Buckeye14Guy Mar 02 '20 at 17:08
  • Do you want to add the values or iterate? The two tasks are not necessarily overlapping in the python interpreter. – Mad Physicist Mar 02 '20 at 18:13
  • Is your real goal to iterate at the slow interpreted level, or to do something fast in compiled numpy, like row mean or sum? If you have arrays try to avoid iteration. Use array class methods instead. – hpaulj Mar 02 '20 at 18:23

1 Answers1

1

First note that your L4 object is a list of lists, rather than a MD array. The list of lists gets converted to a numpy array object in the line a = np.asarray(L4).

To iterate through (in a verbose way), you could do the following. This first iterates through rows, and for each row iterates through the columns:

L4 = [[2, 9, -5], [-1, 0, 4], [3, 1, 2]]
sum = 0
for row in L4:
    for val in row:
        sum+=val
print(sum)

Or follow @Buckeye14Guy's suggestion in the comment for a one-liner

maurera
  • 1,519
  • 1
  • 15
  • 28
  • One more question. If I wanted to find out the total # of elements that i had to iterate. How would I do that? In C++/C#, In my for loop, I'd have { } and I can keep track of the number of elements and add the sum at the same time. – software is fun Mar 02 '20 at 17:22
  • initialize a `count = 0` variable like @maurera did (with `sum = 0`) and in the loop just do `count +=1`. same thing as `sum` but instead you are not adding `val`, just 1. Also I would suggest using a different name than `sum` since that's technically a reserved name – Buckeye14Guy Mar 02 '20 at 17:26
  • How about just `sum(e for row in L4 for e in row)`? – Mad Physicist Mar 02 '20 at 18:12