删除冗余/压缩代码



下面的两个代码示例都是我遇到的一个问题的旧示例,我在一个数字列表中迭代,以找到符合条件列表的数字,但除了之外,找不到一种巧妙的表达方式

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

但我希望有一个更整洁/更简单的方式。

您可以使用类似以下的生成器表达式

def f(n):
    return x%n
if all(f(element) for element in lst):
    ...

如果函数/计算不是太复杂,你可以把它放在中

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

如果您可以在生成器表达式中表达条件,那么内置函数all可以简化这一点:

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

它返回一个布尔结果,指示其可迭代参数的所有元素是否都是True,一旦其中一个元素是False,就会短路结束求值。

这是我在过去一个小时左右看到的第二个问题,all是答案——肯定是悬而未决的问题。

最新更新