Python 使用列表编写包含大量异常的if行
我在Python 使用列表编写包含大量异常的if行,python,list,if-statement,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() titleList = ["Aide", "A
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()
titleList = ["Aide", "Accessibilite", "iphone" , "android", "windows", "applications", "RSS:"]
if all(title != x for x in titleList):
do_stuff()
我如何写这行来使用列表
我试过:
for a in ["Aide", "Accessibilité", "iphone" , "android", "windows", "applications", "RSS:"]:
if title != a:
do_stuff()
但是这个方法为每个a
调用do\u stuff()
,所以这不是我想要的
我该怎么做?谢谢你可以这样写:
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:"]):
...
根据jonrsharpe的建议,您可以做如下操作:
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()
titleList = ["Aide", "Accessibilite", "iphone" , "android", "windows", "applications", "RSS:"]
if all(title != x for x in titleList):
do_stuff()
编辑: 或者,这要简单得多(Tanveer Alam指出了这一点):
为什么我不一开始就写出来。。。可能需要一些非常认真的自我反省。在
do_stuff()
之后添加一个break
以在第一次匹配后停止for循环。如果没有(在[“助手”、“易访问性”、“iphone”、“android”、“windows”、“应用程序”、“RSS:]”中的a):
这将起作用。不需要迭代。@TanveerAlam这不一定是等价的。我认为OP需要。@jornsharpe然后它必须被迭代。谢谢。两种解决方案都很好,使用all()
,这一个对我来说更容易。谢谢