2012-11-22 42 views
1

我有一個依賴於argparse的腳本。腳本的主體有這樣的陳述:if語句中的幾個參數

if results.short == True and results.verbose == False and results.verbose2 == False and results.list == False and results.true == False: 

是否有任何簡短的方法來做到這一點?假設我有超過5個參數,在每個陳述中輸入每個參數似乎都是重複的工作。

不能,如果這樣做:

if results.short == True and "results.%s"== False % (everyotherresults.something): 

我寫的Python 2.7

+0

只需使用'如果results.short而不是%(東西)' 「的結果%s的。」但是,如果它很麻煩,你可以把所有的情況放在一本字典中並遍歷它。 –

回答

4

你不應該比較bool在布爾表達式,如:

if (results.short 
    and not results.verbose 
    and not results.verbose2 
    and not results.list 
    and not results.true): 
+0

甚至更​​短的像這樣'if results.short and not(results.verbose and results.verbose2 and results.list and results.true)' – solarc

+1

er ... no;提取不會是:'result.short而不是(result.verbose或...)'http://en.wikipedia.org/wiki/De_Morgan%27s_laws – SingleNegationElimination

+0

對,它滑倒我的大腦 – solarc

4

您可以在列表中使用any功能,並且所有的參數從第二移動在列表中: -

if results.short and \ 
    not any([results.verbose, results.verbose2, results.list, results.true]): 

any函數返回True如果在列表中的至少一個值是True。因此,只需使用not any,如果列表中的所有值都是False,則將返回True

是的,你不需要比較布爾值與TrueFalse

+1

-1用於測試與True的相等性。 – Marcin

+0

@Marcin。啊!抱歉。只是一個複製粘貼問題。 –

+0

可能更好一些:'如果results.short ==爲真並且沒有任何([項目在結果中的項目]):' – EyalAr