gpt4 book ai didi

python - 'if not'

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:12 25 4
gpt4 key购买 nike

下面的代码

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))

关于 python - 'if not',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42489081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com