Skip to main content
 首页 » 编程设计

python之如何检查列表中的所有字符串

2025年05月04日2052php

website = str(raw_input('Website: ')) 
palavras_chaves = ['joomla', 'Joomla'] 
palavras_chaves2 = ['wordpress', 'Wordpress', 'WordPress', 'wp']     
abrindo = urllib2.urlopen(website) 
abrindo = abrindo.read() 
if palavras_chaves[0] and palavras_chaves[1] in abrindo: 
    print '\nÉ um joomla!' 
 
elif palavras_chaves2[0] and palavras_chaves2[1] and palavras_chaves2[2] and palavras_chaves2[3] in abrindo:         
    print '\nÉ um wordpress!' 
 
else: 
    print '\nÉ um CMS desconhecido!' 

我想知道如何在不指定的情况下检查所有字符串。看起来很简单,但我尝试了我想到的所有方法,但没有成功。

请您参考如下方法:

正如@fourtheye 指出的那样,您需要内置的 all()函数在这里,您可以利用它和列表理解来完成如下所述的工作。

那么试试这个:

if all(i in abrindo for i in palavras_chaves): 
    print '\nÉ um joomla!' 
 
elif all(i in abrindo for i in palavras_chaves2): 
    print '\nÉ um wordpress!' 
else: 
    print '\nÉ um CMS desconhecido!' 

编辑:

我认为如果您像这样手动操作:

if palavras_chaves[0] and palavras_chaves[1] in abrindo: 

之所以有效,是因为 palavras_chaves[1] 在 abrindo 中,但是 palavras_chaves[0] 可能不在 abrindo 中> 但是当你使用 all() 时,palavras_chaves 中的所有字符串 have 都在 abrindo 中,以防万一一个字符串不在 abrindo 中,失败!

看到这个例子,你试图做这样的事情,你希望它返回 'Works as expected' 然而它返回相反的结果

>>> if 'Hey' and 'Bye' in 'Bye': 
...     print 'Not expected right?' 
... else: 
...     print 'Works as expected' 
...      
#Not expected right? 

但是使用all():

if all(i in 'Bye'for i in ['Hey','Bye']): 
    print 'Not expected right?' 
else: 
    print 'Works as expected' 
#Works as expected