如何在Python中理解“无与否",“无与否",“无与否",“无与否"的结果? [英] How to understand the result of `None or False`, `False or None`, `None and False`, `False and None` in Python?

查看:51
本文介绍了如何在Python中理解“无与否",“无与否",“无与否",“无与否"的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我理解了Python中的这两个单例值,直到看到有人在代码中使用 return l1或l2 ,其中l1和l2都是链表对象,并且他想如果不是,则返回l1,否则返回l2.

I thought I understood these two singleton values in Python until I saw someone using return l1 or l2 in the code, where both l1 and l2 are linked list object, and (s)he wanted to return l1 if it is not None, otherwise, return l2.

这段代码很不错,因为它很短并且看起来很容易理解.然后,我写一些代码来弄清楚这里要做什么.

This piece of code is good because it is quite short and seems easy to understand. Then, I write some code to figure out what is going one here.

print ( True or 'arbitrary' ) #True
print ( False or 'arbitrary') #arbitrary
print ( None or 'arbitrary' ) #arbitrary

打印结果符合预期.但是,当我尝试将 None False 放在一起时.发生了非常奇怪的事情.

The printed results are as expected. However, when I try to put None and False together. Something really weird happened.

print ( False or None ) #None
print ( None or False ) #False
print ( None or False or True) #True

所以,我猜想返回A或B 的规则是:

So, my guess the rules of return A or B are:

  • 按顺序返回第一个True(不是None,不是False)值(第一个A,然后是B)

  • return the first True (not None, Not False) value in order (First A and then B)

如果没有True值,则将返回最后一个值.

if there is no True value, then the last value will be returned.

最后,我运行此代码来验证我的猜测.

At last, I run this code to verify my guess.

print ( None or False or True or None) # True
print ( None or False or None) # None
print ( False or None or False) # False

结果似乎证明了我的理论.但是还有人有更多解释吗?

The results seem to prove my theory. But anyone has more explanation?

另外,当我使用时,我得到了一些有趣的东西.为什么?

Also, I got something interesting when I use and. Why?

print ( None and False) #None
print ( False and None) #False

推荐答案

最简单的答案是和"返回第一个假值或最后一个真值,而或"返回第一个真值或最后一个假答案.

The short answer is that 'and' returns the first false value or last true value and 'or' returns the first true or last false answer.

>>> None or False
False
>>> False or None
>>> False and None
False
>>> None and False

...

>>> 0 or 3 or 4
3
>>> 5 and 0 and 6
0
>>> 5 and 0 or 6
6
>>> False or {} or 0
0
>>> 3 and 4 and 5
5

这篇关于如何在Python中理解“无与否",“无与否",“无与否",“无与否"的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆