Python and or ?A:B
2016-03-26 12:17
323 查看
python and 和 or
2013-06-29 17:35 by youxin, 103 阅读, 0 评论, 收藏, 编辑在Python 中,and 和 or 执行布尔逻辑演算,如你所期待的一样。但是它们并不返回布尔值,而是返回它们实际进行比较的值之一。
例 4.15. and 介绍
>>> 'a' and 'b'
'b' >>> '' and 'b'
'' >>> 'a' and 'b' and 'c'
'c'
例 4.16. or 介绍
>>> 'a' or 'b'
'a' >>> '' or 'b'
'b' >>> '' or [] or {}
{} >>> def sidefx(): ... print "in sidefx()" ... return 1 >>> 'a' or sidefx()
'a'
4.6.1. 使用 and-or 技巧
例 4.17. and-or 技巧介绍
>>> a = "first" >>> b = "second" >>> 1 and a or b
'first' >>> 0 and a or b
'second'
这个语法看起来类似于 C 语言中的 bool ? a : b 表达式。整个表达式从左到右进行演算,所以先进行 and 表达式的演算。1 and 'first' 演算值为 'first',然后 'first' or 'second' 的演算值为 'first'。 | |
0 and 'first' 演算值为 False,然后 0 or 'second' 演算值为 'second'。 |
例 4.18. and-or 技巧无效的场合
>>> a = "" >>> b = "second" >>> 1 and a or b
'second'
由于 a 是一个空字符串,在 Python 的布尔环境中空字符串被认为是假的,1 and '' 的演算值为 '',最后 '' or 'second' 的演算值为 'second'。噢!这个值并不是你想要的。 |
在 and-or 技巧后面真正的技巧是,确保 a 的值决不会为假。最常用的方式是使 a 成为 [a] 、 b 成为 [b],然后使用返回值列表的第一个元素,应该是 a 或 b中的某一个。
例 4.19. 安全使用 and-or 技巧
>>> a = "" >>> b = "second" >>> (1 and [a] or [b])[0]
''
由于 [a] 是一个非空列表,所以它决不会为假。即使 a 是 0 或者 '' 或者其它假值,列表 [a] 也为真,因为它有一个元素。 |
进一步阅读
Python Cookbook 讨论了其它的 and-or 技巧。转自:http://woodpecker.org.cn/diveintopython/power_of_introspection/and_or.html
相关文章推荐
- Python——sorted
- Json概述以及python对json的相关操作
- Python MySQLdb 使用utf-8 编码插入中文数据
- LeetCode 292. Nim Game
- Python学习笔记(一)——Python函数的定义和使用
- python 标准类型内建函数
- 共有11款Python 中文分词库开源软件
- Python——sys.argv
- Python图像处理库PIL中快速傅里叶变换FFT的实现(一)
- Python入门 之 迭代
- ubuntu上怎么设置默认python命令是执行python3而不是python2
- Python入门 之 切片
- Python入门 之 函数
- 【python小练】0005
- python中的用来定制类的特殊方法的含义
- Python 基础—— pickle 模块
- Python 基础 —— str
- Python 基础—— operator 模块
- Python debug —— 逻辑错误(三)
- pymouse 控制鼠标。