Python 一定有更好的办法

Python 一定有更好的办法,python,modulo,Python,Modulo,在Python3中有没有更惯用的方法来完成以下任务 if i%1 == 0 and i%2 == 0 and i%3 == 0 and i%4 == 0 and i%5 == 0 and i%6 == 0 and i%7 == 0 and i%8 == 0 and i%9 == 0 and i%10 == 0 and i%11 == 0 and i%12 == 0 and i%13 == 0 and i%14 == 0 and i%15 == 0 and i%16 == 0 and i%17 =

在Python3中有没有更惯用的方法来完成以下任务

if i%1 == 0 and i%2 == 0 and i%3 == 0 and i%4 == 0 and i%5 == 0 and i%6 == 0 and i%7 == 0 and i%8 == 0 and i%9 == 0 and i%10 == 0 and i%11 == 0 and i%12 == 0 and i%13 == 0 and i%14 == 0 and i%15 == 0 and i%16 == 0 and i%17 == 0 and i%18 == 0 and i%19 == 0 and i%20 == 0:
我试图找到最小的正数,它可以被1到20的所有数整除。我不是在寻找新的解决方案。我正在寻找一种更简洁的方式来表达我在上面所做的事情。

是的,与以下内容一起使用:

如果所有
i%j==0
,它将返回True,否则如果
i%j
有任何余数,它将短路并返回False。另外,检查
是否i%1
是多余的,以便可以从2开始

或者反过来,检查是否没有带余数的
i%j

if not any(i % j for j in range(2, 21)):
或者,如果您更喜欢功能性:


您可以将
all
函数与列表理解(或者更好的是)生成器表达式结合使用:

if all(i%(1 + j) == 0 for j in range(20)):

在while循环中使用for循环

num = 1;
while(True): #keeps going until it finds the number
    b = True #remains true as long as it is divisible by div
    for div in range(1,21):
        if not (num % div == 0):
            b = False #number was not divisible, therefore b is now false
            num += 1
            break
    if(b): #b means num was divisible by all numbers.
        break
print(num)

尝试使用
for
循环。另外,请格式化您的代码。或者在Py2上,为获得性能方面的轻度优势,
xrange
。不过,考虑到射程很小,这也没什么大不了的。@ShadowRanger,没错,补充了一条评论。
if all(i%(1 + j) == 0 for j in range(20)):
num = 1;
while(True): #keeps going until it finds the number
    b = True #remains true as long as it is divisible by div
    for div in range(1,21):
        if not (num % div == 0):
            b = False #number was not divisible, therefore b is now false
            num += 1
            break
    if(b): #b means num was divisible by all numbers.
        break
print(num)