Python中没有下面这样的三目运算符:
desc = a == 0 ? "zero" : "not_zero"
但是可以用其他的方式来实现:
1, if else表达式
语法: 为真时的值 if 条件 else 为假时的值
a = 10 b = "zero" if a == 0 else "not_zero" print(type(b), b) # <class 'str'> not_zero
注意下面这样的写法:if else表达式前后出现逗号分隔的内容,将使结果变成tuple
a = 10 b = "aaa", "zero" if a == 0 else "not_zero", "bbb" print(type(b), b) # <class 'tuple'> ('aaa', 'not_zero', 'bbb')
2, and or逻辑运算
a = 10 c = a == 0 and "zero" or "not_zero" print(type(c), c) # <class 'str'> not_zero
下面的写法以后看到要认识:
推导式+if else表达式
my_list = ['a', 'bb', 'ccc'] result = tuple(elem[:2] if len(elem)>2 else elem for elem in my_list) print(type(result), result) # <class 'tuple'> ('a', 'bb', 'cc')
参考
Python三目运算符(三元运算符)用法详解(含Python代码)_python三元运算符_旅途中的宽~的博客-CSDN博客
标签:运算,Python,else,运算符,zero,三目,print From: https://www.cnblogs.com/sailJs/p/17705446.html