以下条件给出相同的结果。两者之间是否有任何性能差异(或其他差异)?
1。
if (x != None) and (y != None):
# Proceed
2。
if (x and y) is not None:
# Proceed
程序员的妻子问他:早餐要吃香肠还是培根?-是的,他回答。(一个真实的故事)。
在日常工作中使用布尔结构时,我们倾向于跳过通用部分,从而X(Y) @ X(Z)
变成X @ (Y,Z)
:
Her bunny is happy and her hamster is happy (1)
是相同的
Her bunny and her hamster are happy
但是,在编程中,我们不能像这样收缩事情。第一句话
bunny == happy and hamster == happy
如果两只宠物都很好,那将是正确的。第二句话直译为:
(bunny and hamster) == happy
在这里,(bunny and hamster)
评估为
- a falsy value, if she's got no bunny
- the hamster otherwise
所以(bunny and hamster) == happy
实际上读为:
She's got a bunny and her hamster is happy
这与陈述(1)完全不同
在python中:
>>> happy = 1
>>> sad = 2
>>> bunny = sad
>>> hamster = happy
>>> bunny == happy and hamster == happy
False
>>> (bunny and hamster) == happy
True
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句