简体   繁体   中英

How to simplify multiple conditions in Python

I wrote a script in python that parses some strings.

The problem is that I need to check if the string contains some parts. The way I found is not smart enough.

Here is my code:

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

Is there a way to optimize this? I have 6 other checks for this condition.

You can use any function:

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

Use a generator with any() or all() :

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

In Python 3, you could also make use of map() being lazy:

if not all(map(message.__contains__, ('CondA', 'CondB', ...))):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM