使用list写一个带有很多异常的if行

时间:2015-01-02 09:43:03

标签: python list if-statement

我在if这样的行中有很多例外:

if "Aide" not in title and "Accessibilité" not in title and "iphone" not in title and "android" not in title and "windows" not in title and "applications" not in title and "RSS:" not in title:
    do_stuff()

如何编写此行以使用列表?

我试过了:

for a in ["Aide", "Accessibilité", "iphone" , "android", "windows", "applications", "RSS:"]:
   if title != a:
      do_stuff()

但是这个方法会为每个do_stuff()调用a,所以它不是我想要的...

我该怎么做?感谢

2 个答案:

答案 0 :(得分:2)

你可以这样写:

def contains_any(s, it):
    return any(word in s for word in it)

if not contains_any(title, ["Aide", "Accessibilité", "iphone" , "android",
                            "windows", "applications", "RSS:"]):
    ...

答案 1 :(得分:2)

使用jonrsharpe的建议,你可以这样做:

titleList = ["Aide", "Accessibilite", "iphone" , "android", "windows", "applications", "RSS:"]
if all(title != x for x in titleList):
     do_stuff()

修改

或者,这更简单(Tanveer Alam指出了这一点):

if title not in titleList:
     do_stuff()

为什么我不首先写出来......可能需要一些非常认真的灵魂搜索。