消除冗余/压缩Cod

2024-04-27 03:10:24 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的两个代码示例都是我遇到的一个问题的老例子,我正在遍历一个数字列表,以找到符合一个条件列表的数字,但找不到一个简洁的方式来表达它,除了:

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

但我希望有一个更整洁/更简单的方法。你知道吗


Tags: andthe方法in列表forifcount
2条回答

如果可以在生成器表达式中表示条件,则内置函数all可以简化此过程:

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

它返回一个布尔结果,指示它的iterable参数的所有元素是否都是True,一个元素是False就立即结束计算。你知道吗

这是我在过去一个小时左右看到的第二个问题,all就是答案——一定是空气中有什么东西。你知道吗

可以使用这样的生成器表达式

def f(n):
    return x%n

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

如果函数/计算不太复杂,您可以将其内联

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

相关问题 更多 >