Python三元运算

来源:互联网 发布:网络倾听者兼职 编辑:程序博客网 时间:2024/05/29 03:38

Python三元运算

Python没有类似与C语言系列的三元运算符<condition> ? <expression1>: <expression2>,但可以通过<condition> and <expression1> or <expression2>或者<expression1> if <condition> else <expression2>方式实现三元运算。关于Python三元运算,Python社区很早就开始讨论了[1]
具体使用如下:
and/or使用

result1 = True and 'test_true' or 'test_false'    # result1 = test_trues = 1result2 = s == 2 and 'test_true' or 'test_false'    # result2 = test_false

if/else使用

result1 = 'test_true' if True else 'test_false'    # result1 = test_trues = 1result2 = 'test_true' if s == 2 else 'test_false'    # result2 = test_false

在使用and/or时需要特别注意,虽然and/or比较简洁,但容易出错比如

result1 = True and False or True    # result1 = Trues = 1result2 = s !=1 and False or True   # result2 = Trues = 2result3 = s !=1 and False or True   # result3 = True

因此进行三元运算时,建议使用if/else

参考引用

[1] PEP 308 – Conditional Expressions