如何在Python中简化多个条件

3

我用Python写了一个脚本来解析一些字符串。

问题是我需要检查字符串是否包含某些部分,但我找到的方法不够聪明。

以下是我的代码:

if ("CondA" not in message) or ("CondB" not in message) or ("CondC" not in message) or ...:

有没有优化这个的方法?我还有6个其他检查需要进行此条件。
2个回答

2
您可以使用any函数:
if any(c not in message for c in ("CondA", "CondB", "CondC")):
    ...

我可以在循环中使用列表吗? 例如:for c in list - GiuseppeP

2

使用带有any()all()的生成器:

if any(c not in message for c in ('CondA', 'CondB', ...)):
    ...

在Python 3中,你还可以利用map()的惰性特性:
if not all(map(message.__contains__, ('CondA', 'CondB', ...))):

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接