Reputation: 316
I have a code which goes like this:
flag = 0
if A == 'string1':
flag = 1
if B == 'string2':
flag = 1
if C == 'string3':
flag = 1
Is there a way to create a list of the rules I want to check, check whether at least one is true, and set flag
to 1? For example,
D = [A == 'string1', B == 'string2', C=='string3']
if D:
flag = 1
Upvotes: 0
Views: 15010
Reputation: 875
You were almost there.
D = [A == 'string1', B == 'string2', C=='string3']
if True in D:
flag = 1
D has the boolean values of each test, True in D tests if any of them are True.
Edit: I wrote this over a year ago, but someone upvoted it recently, and looking back at it, I now know there is a built in that saves a few keystrokes.
We can write the code above as
D = [A == 'string1', B == 'string2', C=='string3']
if any(D):
flag = 1
Upvotes: 2
Reputation: 77837
if A == 'string1' or \
B == 'string2' or \
C == 'string3':
flag = True # use Boolean values, not coded numbers
Or simply assign the result of the Boolean expression:
flag = A == 'string1' or \
B == 'string2' or \
C == 'string3'
This last one will give flag
the proper value, either True
or False
.
If you need a list of variables and values, try something like this:
vars = [A, B, C]
vals = ['string1', 'string2', 'string3']
flag = any([vars[i] == vals[i] for i in range(len(vars)) ])
... or make a dictionary of those same items (courtesy of codehearts
):
checks = { 'string1': A, 'string2': B, 'string3': C }
flag = any([var == val for var, val in checks.iteritems() ])
... or zip
the list into pairs (tuples) per wwii
:
flag = any(a == b for a, b in zip(vars, vals))
You can extend the list sizes as far as you want. This assumes that each "rule" is simply checking paired values.
Upvotes: 4
Reputation: 948
You can use any:
if any((A == 'string1', B == 'string2', C=='string3')):
flag = 1
Upvotes: 3