用lis写一个异常较多的if行

2024-06-16 14:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但是这个方法为每个a调用do_stuff(),所以这不是我想要的。。。你知道吗

我该怎么做?谢谢


Tags: andin列表iftitlewindowsnotdo
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:"]):
    ...

利用jornsharpe的建议,你可以这样做:

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

为什么我一开始不写出来。。。可能需要一些非常认真的反省。你知道吗

相关问题 更多 >