python检查列表中是否存在值

时间:2015-03-27 20:51:24

标签: python

无法理解这一点。我想检查列表的内容以获取一组值。如果因为该值不存在,我不应该落在条件内。

以下列表包含: ['pm_pmdo','pm_pmco','shv','dsv','pmv']

检查以下内容:she,dse,pme

里面发现了一个?

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()

3 个答案:

答案 0 :(得分:2)

if any(role in self.users_roles for role in (self.SHE, self.PME, self.SHE)):

答案 1 :(得分:1)

如果订单无关紧要,

sets是快速成员资格测试的好容器:

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()

答案 2 :(得分:0)

使用any短路返回True如果我们找到匹配或评估为False否则:

if any(s in self.users_roles for s in (self.DSE , self.PME , self.SHE ))

您的代码始终评估为True,因为if self.DSE基本上正在检查if bool(self.DSE),对于任何非空字符串,它总是会评估为True,对于{{self.PME 1}}和self.SHE

In [21]: bool("foo") # will be the same for all non empty strings
Out[21]: True

In [22]: bool("")
Out[22]: False

您还可以设置self.users_roles一套并使用set.intersection

self.users_roles = {'pm_pmdo', 'pm_pmco', 'shv', 'dsv', 'pmv'}

if self.users_roles.intersection([self.DSE, self.PME, self.SHE])