and or类比c中的 bool?a :b

a = "heaven"

b = "hell"

c = True and a or b     print c

d = False and a or b    print d

输出: heaven      hell

所以bool and a or b类比c中的bool?a:b,当bool条件为真时,结果是a;当bool条件为假时,结果是b。 注意:由于这个语句靠的是python的逻辑关系实现的,所以要保证a不为0或“”。 否则: a = "" b = "hell" c = True and a or b print c 得到的结果不是""而是"hell"。因为""和"hell"做or的结果是"hell"。 然后这里有一个常见的解决方法:使 a 成为 [a] 、 b 成为 [b]由于[a]是一个非空列表,所以它决不会为假。即使a是0或者''或者其它假值,列表[a]也为真,因为它有一个元素。

原文地址:https://www.cnblogs.com/wangshen31/p/6368475.html