1

Why doesn't the following code work?

import numpy

grid = numpy.matrix([[1,0,1,1],[1,1,0,0],[1,0,1,0],[0,0,0,1]])
i = 0
for line in grid:
    for block in line:
        if block == 1:
            i += 1    
print("Grid has " + str(i) + " times number 1")

I thought it's gonna first cycle through every line and then every element of the line and compare it with 1, but I get this error:

Traceback (most recent call last):
File "python", line 7, in <module>
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()
1
  • If you had used numpy.array instead of numpy.matrix, you wouldn't have had this problem. Seriously, numpy.matrix isn't worth it. Commented Dec 12, 2017 at 19:31

1 Answer 1

1

Iterating through a numpy.matrix matrix produces 1-row numpy.matrix matrices, one for each row.

Iterating over a 1-row numpy.matrix matrix produces a 1-row numpy.matrix matrix, not the individual cells.

Don't use numpy.matrix. It's not at all worth it. Also, don't loop over NumPy objects at all if you can help it:

grid = numpy.array([[1,0,1,1],[1,1,0,0],[1,0,1,0],[0,0,0,1]])
i = grid.sum()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.