一定有更好的方法

There has to be a better way

在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 的所有数字整除的最小正数。我不是在寻找新的解决方案。我正在寻找一种更简洁的方式来表达我在上面所做的事情。

是使用all with range:

if all(i % j == 0 for j in range(1, 21)): # python2 -> xrange(2, 21) 
   # do whatever

如果全部i % j == 0,则return为真否则短路和return False 如果 i % j 有余数。此外,检查 if i % 1 是多余的,因此您可以从 2.

开始

或者反过来,检查是否有notanyi % j有余数。

if not any(i % j for j in range(2, 21)):

或者如果您更喜欢功能性

if not any(map(i.__mod__, 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)