[英]How to simplify multiple conditions in Python
我在python中編寫了一個解析一些字符串的腳本。
問題是我需要檢查字符串是否包含某些部分。 我發現的方式不夠聰明。
這是我的代碼:
if ("CondA" not in message) or ("CondB" not in message) or ("CondC" not in message) or ...:
有沒有辦法優化這個? 我有6個其他檢查這種情況。
你可以使用any
功能:
if any(c not in message for c in ("CondA", "CondB", "CondC")):
...
使用帶有any()
或all()
的生成器:
if any(c not in message for c in ('CondA', 'CondB', ...)):
...
在Python 3中,您還可以使用map()
進行延遲:
if not all(map(message.__contains__, ('CondA', 'CondB', ...))):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.