form "if" in C++

Possible Duplicate:
Python Ternary Operator

Is there a way to write this C/C++ code in Python? a = (b == true ? "123" : "456" )


a = '123' if b else '456'

While a = 'foo' if True else 'bar' is the more modern way of doing the ternary if statement (python 2.5+), a 1-to-1 equivalent of your version might be:

a = (b == True and "123" or "456" )

... which in python should be shortened to:

a = b is True and "123" or "456"

... or if you simply want to test the truthfulness of b's value in general...

a = b and "123" or "456"

? : ? : can literally be swapped out for and or


我的神秘版本...

a = ['123', '456'][b == True]
链接地址: http://www.djcxy.com/p/7384.html

上一篇: 如何将if / else压缩成Python中的一行?

下一篇: 在C ++中形成“if”