Python 的and 运算

obj1 and obj2 and obj3 的返回值是 这个语句执行的最后的一个obj 的值。

>>> 'a' and 'b' and 'c'
'c'
>>> 'a' and False and 'c'
False
>>> False and 'b' and 'c'
False

这个特性可以让有些代码写的更加简洁,例如['A', None, 'Bar'] 我们需要讲里面的内容全部变成小写,如果遇到None, 就转换成''

b = []
for x in a:
    if x is None:
        b.append('')
    else:
        b.append(x.lower())

更加紧凑的写法是:
[x is not None and x.lower() or '' for x in ['A', None, 'Bar']]

posted @ 2015-01-15 12:22  zhifan  阅读(301)  评论(0)    收藏  举报