Python - '如果不是'

Geo*_*rge 1 python

以下代码

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

print(sum([i for i in range(1, 1000) if not (i%3 and i%5)]))
Run Code Online (Sandbox Code Playgroud)

做同样的事.

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

我所说的是,在第一个代码中i % 3 == 0 or i % 5 == 0必须单独声明,而在没有第二个代码的情况下实现同样的事情== 0.

Roc*_*mat 12

使用De Morgan定律:

i % 3 == 0 or i % 5 == 0
Run Code Online (Sandbox Code Playgroud)

是相同的:

not (i % 3 != 0 and i % 5 != 0)
Run Code Online (Sandbox Code Playgroud)

在python中,当将数字转换为布尔值时,任何非零值都会变为True.

因此,您可以使用,而不是i % 3 != 0在其中if,i % 3因为如果它0False,它将是非零,它将是True.

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

PS sum()可以将生成器作为参数,所以你实际上可以这样做:

sum(i for i in range(1, 1000) if not (i%3 and i%5))
Run Code Online (Sandbox Code Playgroud)