Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching integers in a loop in python

In my example code below, I want to produce an indication of whether a predefined list of numbers either matches or does not match an iterable that I'm looping through. This is a simplified example of my problem.

Unfortunately my code below does not do what I'm expecting, and probably I'm missing something simple. In my real application this is done with extremely large 1 dimensional arrays with varied output, but this demonstrates it in a simple text way that is easy to reproduce.

Maybe I should also add that I'm using Python 2.7.5.

match = [1, 3, 4]
volumes=10

def vector_covariates(match, volumes):
    for i in range(volumes):
        if i == match:
            print "[*]"
        else:
            print "[ ]" 

vector_covariates(match, volumes)

When run, it outputs:

 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ] 

Whereas the "correct" output should be

 [*]
 [ ]
 [*]
 [*]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
 [ ]
like image 918
J R Avatar asked Dec 29 '25 07:12

J R


1 Answers

Use in not ==:

if i in match:

As it is, you're checking the value of i (a number) to a list, and those two are not going to be the same!

like image 152
SlightlyCuban Avatar answered Dec 30 '25 21:12

SlightlyCuban



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!