Home > front end >  Python boolean behavior at arrays
Python boolean behavior at arrays

Time:06-08

I have a question about an arrays and loops. I'd like to get the information, if a specific element in the array has a certain value and then print weather it is true or false.

data = [[1,2,3],[4,5,6]]
data = np.array(data)
[row,col] = data[:,:].shape

for i in range(row-1):
    for j in range(col-1):
        print(data[i][j] == 3)

But the output is

False
False

But this seems not right, because the matrix has 6 values and I only got 2 returned

Using

print(data == 3)

generates

[[False False  True]
 [False False False]]

How can I fix the for-loops?

CodePudding user response:

You need to remove the -1, I believe this is what you look for

import numpy as np
data = [[1,2,3],[4,5,6]]
data = np.array(data)
[row,col] = data[:,:].shape
for i in range(row):
    for j in range(col):
        print(data[i][j] == 3)

CodePudding user response:

You should be using range(row) instead of range(row-1) and likewise for col.

Range is exclusive of the value you pass as the argument. In your example row = 2, therefore using range(row-1) is actually range(1), which will return the iterable [0]. col = 3, so for range(col-1) your doing range(2) which returns [0, 1]. Your current loop is only looking at the first row and first two columns, hence only 2 values returned instead of six.

  • Related