下面的两个代码示例都是我遇到的问题的旧示例,我正在遍历数字列表以查找符合条件列表的数字,但找不到一种简洁的方式来表达它,除了:
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):
...
如果函数/计算不是太复杂,直接inline就可以了
if all(x % element for element in lst):
...
