2013-12-10 107 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--适用于各种各样问题的简单工具。 –