下面的两个代码示例都是我遇到的一个问题的老例子,我正在遍历一个数字列表,以找到符合一个条件列表的数字,但找不到一个简洁的方式来表达它,除了:
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
但我希望有一个更整洁/更简单的方法。你知道吗
如果可以在生成器表达式中表示条件,则内置函数
all
可以简化此过程:它返回一个布尔结果,指示它的iterable参数的所有元素是否都是
True
,一个元素是False
就立即结束计算。你知道吗这是我在过去一个小时左右看到的第二个问题,
all
就是答案——一定是空气中有什么东西。你知道吗可以使用这样的生成器表达式
如果函数/计算不太复杂,您可以将其内联
相关问题 更多 >
编程相关推荐