Skip to main content
 首页 » 编程设计

python之'if not'

2025年05月04日14bhlsheji

下面的代码

multiples = [] 
for i in range(1,1000): 
    if i % 3 == 0 or i % 5 == 0: 
        multiples.append(i) 
addition = sum(multiples) 
print addition 

和

print(sum([i for i in range(1, 1000) if not (i%3 and i%5)])) 

做同样的事情。

现在如何在第二个代码中计算 if not 部分?

我的意思是,在第一个代码中,i % 3 == 0 or i % 5 == 0 必须专门声明,而第二个代码实现了同样的事情没有 == 0。

请您参考如下方法:

使用 De Morgan's laws :

i % 3 == 0 or i % 5 == 0 

等同于:

not (i % 3 != 0 and i % 5 != 0) 

在 python 中,当将数字转换为 bool 值时,任何非零值都变为 True。

因此,与其在 if 中执行 i % 3 != 0,不如使用 i % 3,因为如果它是 0 它将是 False,如果它不是零,它将是 True。

这是 python 的真值表:https://docs.python.org/3.6/library/stdtypes.html#truth

附言sum() 可以将生成器作为参数,因此您实际上可以这样做:

sum(i for i in range(1, 1000) if not (i%3 and i%5))