如何缩短此条件语句(检查数字是否可被 1-10 的所有值整除)python
how to shorten this conditional statement (checking if number is divisible by all values from 1-10) python
如何在 Python 中缩短这个条件语句?
if x % 1 == 0 and x % 2 == 0 and x % 3 == 0 and x % 4 == 0 and x % 5 == 0
and x % 6 == 0 and x % 7 == 0
and x % 8 == 0 and x % 9 == 0 and x % 10 == 0:
我试过:
for x in range(some range):
for y in range(1,11):
if x % y == 0:
do something
然而,这只是检查 x 中的所有数字是否在每个循环中分别被 1、2、3 等整除。我希望它被完全检查。
您可以 运行 a for loop
检查条件是否 不 满足其中一个 y。 else
子句仅在 for 循环期间没有发生 break
时执行。
for x in range(some range):
for y in range(1,11):
if x % y != 0:
break
else:
do_something
编辑:进一步解释(在评论中给出)
一旦 y x % y
与 0 不同,就离开内部 for 循环并检查下一个数字 x。内层for循环的else
只有在整个内层for循环运行没有中断后才会执行,所以当所有y都满足条件x % y == 0
.
使用all
with a generator expression:
all(x%n == 0 for n in range(1, 11))
完整示例:
test_numbers = (37, 300, 2520, 5041, 17640)
for x in test_numbers:
if all(x%n == 0 for n in range(1, 11)):
print('{} is disible by all integers 1 to 10.'.format(x))
结果:
2520 is disible by all integers 1 to 10.
17640 is disible by all integers 1 to 10.
请注意,all
是高效的,因为它会在遇到 False
值时停止计算。
如何在 Python 中缩短这个条件语句?
if x % 1 == 0 and x % 2 == 0 and x % 3 == 0 and x % 4 == 0 and x % 5 == 0
and x % 6 == 0 and x % 7 == 0
and x % 8 == 0 and x % 9 == 0 and x % 10 == 0:
我试过:
for x in range(some range):
for y in range(1,11):
if x % y == 0:
do something
然而,这只是检查 x 中的所有数字是否在每个循环中分别被 1、2、3 等整除。我希望它被完全检查。
您可以 运行 a for loop
检查条件是否 不 满足其中一个 y。 else
子句仅在 for 循环期间没有发生 break
时执行。
for x in range(some range):
for y in range(1,11):
if x % y != 0:
break
else:
do_something
编辑:进一步解释(在评论中给出)
一旦 y x % y
与 0 不同,就离开内部 for 循环并检查下一个数字 x。内层for循环的else
只有在整个内层for循环运行没有中断后才会执行,所以当所有y都满足条件x % y == 0
.
使用all
with a generator expression:
all(x%n == 0 for n in range(1, 11))
完整示例:
test_numbers = (37, 300, 2520, 5041, 17640)
for x in test_numbers:
if all(x%n == 0 for n in range(1, 11)):
print('{} is disible by all integers 1 to 10.'.format(x))
结果:
2520 is disible by all integers 1 to 10.
17640 is disible by all integers 1 to 10.
请注意,all
是高效的,因为它会在遇到 False
值时停止计算。