Reputation: 31
couldn't get this correct. I want to check the contents of the list for a set of values. I should not be falling inside the conditional if because the value doesn't exist.
Following list contains: ['pm_pmdo', 'pm_pmco', 'shv', 'dsv', 'pmv']
Checking for the following: she, dse, pme
inside found one?
class newfunc(object):
def testfunction(self):
self.DSE = 'dse'
self.PME = 'pme'
self.SHE = 'she'
self.users_roles = ['pm_pmdo', 'pm_pmco', 'shv', 'dsv', 'pmv']
print 'Following list contains:'
print self.users_roles
print 'Checking for the following:'
print self.SHE
print self.DSE
print self.PME
if (self.DSE or self.PME or self.SHE for s in self.users_roles):
#if (self.DSE or self.PME or self.SHE) in self.users_roles:
print "inside found one"
else:
print "outside none found"
if __name__ == '__main__':
runtime = newfunc()
runtime.testfunction()
Upvotes: 1
Views: 1255
Reputation: 123541
sets
are good containers for quick membership testing if order doesn't matter:
class NewFunc(object):
def testfunction(self):
self.DSE = 'dse'
self.PME = 'pme'
self.SHE = 'she'
self.users_roles = {'pm_pmdo', 'pm_pmco', 'shv', 'dsv', 'pmv'}
print 'users_roles:'
print list(self.users_roles)
print 'Checking for the following:'
print self.SHE
print self.DSE
print self.PME
if {self.DSE, self.PME, self.SHE} & self.users_roles:
print "found at least one"
else:
print "none found"
if __name__ == '__main__':
runtime = NewFunc()
runtime.testfunction()
Upvotes: 1
Reputation: 180522
Use any
which short circuits returning True if we do find a match or evaluates to False otherwise:
if any(s in self.users_roles for s in (self.DSE , self.PME , self.SHE ))
Your code always evaluates to True
as if self.DSE
is basically checking if bool(self.DSE)
which will always evaluate to True
for any non empty string, it is the same for self.PME
and self.SHE
.
In [21]: bool("foo") # will be the same for all non empty strings
Out[21]: True
In [22]: bool("")
Out[22]: False
You can also make self.users_roles
a set and use set.intersection
:
self.users_roles = {'pm_pmdo', 'pm_pmco', 'shv', 'dsv', 'pmv'}
if self.users_roles.intersection([self.DSE, self.PME, self.SHE])
Upvotes: 0
Reputation: 184395
if any(role in self.users_roles for role in (self.SHE, self.PME, self.SHE)):
Upvotes: 2