huy*_*huy 111 c++ python syntax
可能重复:
Python三元运算符
有没有办法用Python编写这个C/C++代码?
a = (b == true ? "123" : "456" )
Sil*_*ost 208
a = '123' if b else '456'
Run Code Online (Sandbox Code Playgroud)
jdi*_*jdi 18
虽然a = 'foo' if True else 'bar'
是更现代的方式来执行三元if语句(python 2.5+),但是你的版本的1对1等价物可能是:
a = (b == True and "123" or "456" )
Run Code Online (Sandbox Code Playgroud)
...在python中应缩短为:
a = b is True and "123" or "456"
Run Code Online (Sandbox Code Playgroud)
......或者如果你只想测试一般b值的真实性......
a = b and "123" or "456"
Run Code Online (Sandbox Code Playgroud)
? :
可以从字面上换掉 and or