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
阅读全文
0 0
- python三元运算符
- 【Python】三元运算
- python中的三元运算
- python的三元运算
- Python三元运算
- python 三元运算符
- python的三元运算符
- python中的三元运算符
- python的三元运算符
- Python语言技巧之三元运算符
- python 下的三元运算符
- Python---变量的管理/三元运算
- Python三元运算符替代方案
- 三元运算
- python基础:python循环、三元运算、字典、文件操作
- Python -- 三元表达式(三目运算符)
- python 中的三元表达式(三目运算符)
- python基础3 集合 三元运算 深浅拷贝 函数
- 《Python语言及其应用》读书笔记(9)之第10章系统(关键词:系统)
- iText整合图片和自带表格生成PDF文件(很好用的框架)
- 翻译连载 | 第 9 章:递归(上)-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇
- java.lang.Object.hashCode()方法
- [4-01]linux
- Python三元运算
- SpringBoot 引入包后找不到类
- 第三周【项目3
- websocket的使用方法
- 移动端页面开发时需要注意的一些问题总结
- 使用VSCODE 开发.NET CORE2.0(二)
- mybatis官方介绍
- Java学习笔记之集合(一):Collection集合的方法
- 全新阿里云大学发布! ——阿里巴巴全力打造云生态下的创新人才工场