Home > other >  If condition in python not working properly over 2 dimensional array
If condition in python not working properly over 2 dimensional array

Time:01-17

I need to do is if any value inside my 2D array is greater than 0.3 it must display toxic but what it always does is print non-toxic even if there exist larger values like 0.6 or 0.4. I printed my values from the array just to see if there is an issue with loops but that's alright. I print the correct values

 **for i in range(len( classes)):
      for j in range(len(classes[i])):
            print(classes[i][j])
            if  (classes[i][j] >0.3):
                comment = " toxic"
            else:
                comment = "non toxic"**

CodePudding user response:

One way would be to use the any function, like this:

if any(element > 0.3 for group in classes for element in group):
    comment = "toxic"
else:
    comment = "non-toxic"

CodePudding user response:

I think the issue here is that you are using only 1 variable to handle a list of values. The variable comment is given the string toxic if a number is greater than 0.3 but if the next value in the array is less than 0.3 then the variable comment's value is getting overwritten. If you want to check each variable and store a string depending on the value that was just checked try something like this:

classes_values = []

for i in range(len( classes)):
    classes_values.append([])
    for j in range(len(classes[i])):
        print(classes[i][j])
        if  (classes[i][j] >4):
            comment = " toxic"
        else:
            comment = "non toxic"
        classes_values[i].append(comment)

CodePudding user response:

A better approach would be to use a function:

def contains_toxic(classes):
    for group in classes:
        for element in group:
            if  element > 0.3:
                return True
    return False

you can also use the for.. in construct to make this simpler to understand

However, the any function makes it a single line and is probably better performance, being a built-in function, but you'll need to understand list comprehensions.

istoxic = any(element  > 0.3 for group in classes2 for element in group);
  •  Tags:  
  • Related