python中and-or小技巧
source link: https://www.hi-roy.com/posts/python%E4%B8%ADand-or%E5%B0%8F%E6%8A%80%E5%B7%A7/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
python中and-or小技巧
首先,python中逻辑运算从左到右进行,and运算返回第一个假值,若都为真则返回最后一个真值。or运算返回第一个真值,若都为假则返回最后一个假值。
其次,python中0,(),[],{},None,空字符串都是假。
下面用简单的例子说明一下:
def f():
print "in f"
return False
def t():
print "in t"
return True
def n():
print "in n"
In [105]: r = t() and f() or n()
in t
in f
in n
In [106]: r
In [107]: r = t() and n() or f()
in t
in n
in f
In [108]: r
Out[108]: False
In [111]: r = f() and n() or t()
in f
in t
In [112]: r
Out[112]: True
上面我们定义了3个函数,没返回值的情况下函数会默认返回None。这里有个地方需要注意,虽然函数可以返回true、false、none,但函数本身都是为真的,比如:
In [127]: rr = f and t or n
In [128]: rr
Out[128]: <function __main__.t="">
In [129]: rr = f and n or t
In [130]: rr
Out[130]: <function __main__.n="">
</function></function>
再举个《python简明教程》的例子:
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
processFunc 现在是一个函数,但是它到底是哪一个函数还要取决于 collapse 变量。如果 collapse 为真,processFunc(string) 将压缩空白;否则 processFunc(string) 将返回未改变的参数。
假设我们有一个对象,我们需要先判断这个对象是否存在,如果存在的话则取它的id,就可以这么写:
pid = user and user.id or False
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK