【发布时间】:2010-12-13 18:29:57
【问题描述】:
【问题讨论】:
-
顺便说一下,它被称为三元if。 en.wikipedia.org/wiki/%3F:, en.wikipedia.org/wiki/Ternary_operation
-
...或“条件表达式”
【问题讨论】:
a = '123' if b else '456'
【讨论】:
虽然a = 'foo' if True else 'bar' 是执行三元 if 语句 (python 2.5+) 的更现代方式,但您的版本可能是一对一等效的:
a = (b == True and "123" or "456" )
...在python中应该缩短为:
a = b is True and "123" or "456"
...或者如果您只是想测试 b 值的真实性...
a = b and "123" or "456"
? : 可以直接换成and or
【讨论】:
我的神秘版本...
a = ['123', '456'][b == True]
【讨论】:
True and "foo" or "bar"
请参阅PEP 308 了解更多信息。
【讨论】: