python and or技巧

模拟C中的bool?a:b

格式:

1 and a or b

0 and a or b

e.g.

>>> a = "love"
>>> b = "hate"
>>> 'python' and a or b
'love'
>>> '' and a or b
'hate'

注意:

确保a的值不会为假。

若a为假,会发生什么呢?

>>> a = ''
>>> b = 'hate'
>>> 'python' and a or b
'hate'

我想,这并不是我们想要的。那怎么办呢?

你在使用and-or时,最好确保a不为假,但是这里我还是想告诉你一个小技巧:

1 and [a] or [b]

>>> 'python' and [a] or [b]
['']

这样a决不会为假了。

 

参考: http://diveintopython.org/

你可能感兴趣的:(c,python)