2013-12-08 24 views
3

我在python中編寫了一個腳本來解析一些字符串。如何簡化Python中的多個條件

問題是我需要檢查字符串是否包含某些部分。 我發現的方式不夠智能。

這裏是我的代碼:

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

有沒有辦法來優化呢?我有6個其他檢查這種情況。

回答

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', ...))): 
2

可以使用any功能:

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

我可以在循環中使用一個列表? 例如:對於列表中的c – GiuseppeP

+0

@ user2078176當然可以 – ndpu