February 7, 2006
Python中的r = cond?x:y(转寄)
发信人: Black8 (⑧), 信区: Python
标 题: Python中的r = cond?x:y
发信站: 水木社区 (Tue Feb 7 22:47:08 2006), 转信
c语言中的这个语法,
如果cond=True,r = x 否则 r = y
在Python中有没有相应的表达方法?
我大概实验了一下,下面这个写法也可以:
r = cond and x or y
–
发信人: ghc (sunnavy), 信区: Python标 题: Re: Python中的r = cond?x:y发信站: 水木社区 (Tue Feb 7 23:12:16 2006), 转信
那样写不好,比如:
1?0:3 // get 01 and 0 or 3 # get 3
–
发信人: redhair (lolicon), 信区: Python标 题: Re: Python中的r = cond?x:y发信站: 水木社区 (Tue Feb 7 23:51:03 2006), 转信
r = (cond and [x] or [y])[0]
–
发信人: hotdog9 (每天爱你多一些), 信区: Python标 题: Re: Python中的r = cond?x:y发信站: 水木社区 (Wed Feb 8 10:25:54 2006), 转信
[y,x][bool(cond)]
Filed by
charlie
at 11:00 pm under Python

[...] Python中的and和or Python 中的逻辑运算,and 和 or 并不是像c/c++类的语言一样,返回 true或者 false。他们的返回值(return value)是两个操作符(operantor)中,其中一个的值。 这个特点似乎在同是脚本语言的lua中也是一样。有人还认为这不太正常,有点气愤。 实际上这种设计还是很合乎逻辑的,也有用处。比如以前我曾经不解类似c语言中 condition?a:b 这种语句在python中的写法,在水木上得到指教,用 and 和 or 就可以很简洁地表达出来。 r = cond and x or y Python 2.4文档的 5.10 中也提到了: Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or ‘foo’ yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not ‘foo’ yields False, not ”. 举的例子是:“如果为空(非法值、失败)的话就使用默认值”,简洁的表达。 所以这里的 x and y 可以理解为:先x,“然后再” y。是不是让 and 这个词回归本来的语义了呢? 同理,x or y就是:如果x 不成的话,y (为真)也行啊。 如果上面的 x, y 都是函数的话,x or y or z… 就是 “从左到右执行这些操作,直到其中一个成功为止” 。 x and y and z… 就是“从左到右执行这些操作,有一个失败就拉倒”。 如果 and 和 or 组合起来,意思就更丰富了。 这不正是脚本语言所追求的吗? 不能从c/c++的角度来理解脚本语言。 [...]
PEP 308
true_v if cond else false_v