2013-12-10 102 views
1

下面的兩個代碼示例是一個問題的舊例子,我在其中遍歷數字列表以找到符合條件列表的數字,但找不到表達它的整潔方式的數字爲:上述的刪除冗餘/冷凝代碼

condition1 and condition2 and condition3 and condition4 and condition5 

兩個例子:

if str(x).count("2")==0 and str(x).count("4")==0 and str(x).count("6")==0 and str(x).count("8")==0 and str(x).count("0")==0: 

if x % 11==0 and x % 12 ==0 and x % 13 ==0 and x%14==0 and x %15 == 0 and x%16==0 and x%17==0 and x%18==0 and x%19==0 and x%20==0: 

是否有這樣做的一個簡單的,更簡潔的方式?

我的第一個重試是條件存儲在列表如下圖所示:

list=["2","4","6","8","0"] 
for element in list: 
    #call the function on all elements of the list 
list=[11,12,13,14,15,16,17,18,19,20] 
for element in list: 
    #call the function on all elements of the list 

但我希望一個更整潔的/簡單的方法。

回答

3

您可以用生成器表達式這樣

def f(n): 
    return x%n 

if all(f(element) for element in lst): 
    ... 

如果函數/計算並不複雜,你可以把它內嵌

if all(x % element for element in lst): 
    ... 
3

內置的功能all可以簡化這個,如果你能在一臺發電機表情表達自己的條件:

result = all(x % n == 0 for n in xrange(11, 21)) 

它返回boolean指示是否所有的迭代參數的元素True,只要有一個是False就可以短路結束評估。

這是我在過去一個小時左右見過的第二個問題,all就是答案 - 一定是空中的東西。

+0

其實,我是誰問的一個之前關於所有問題的問題,除非它與這個問題無關! –

+1

這就是你的Python--適用於各種各樣問題的簡單工具。 –