本文目录导读:

我来分享几种Python三元运算的简写方式:
基础三元运算
# 传统写法
if score >= 60:
result = "及格"
else:
result = "不及格"
# 三元运算简写
result = "及格" if score >= 60 else "不及格"
多个条件判断
# 普通写法
if x > 0:
result = "正数"
elif x == 0:
result = "零"
else:
result = "负数"
# 三元运算嵌套(不推荐,可读性差)
result = "正数" if x > 0 else ("零" if x == 0 else "负数")
# 更推荐使用字典
result = {True: "正数", False: "零" if x == 0 else "负数"}[x > 0]
列表推导式中的三元运算
# 批量处理
numbers = [1, -2, 3, -4, 5]
# 传统写法
result = []
for n in numbers:
if n > 0:
result.append("正")
else:
result.append("负")
# 三元运算简写
result = ["正" if n > 0 else "负" for n in numbers]
实战案例
# 1. 判断奇偶性
num = 7
parity = "偶数" if num % 2 == 0 else "奇数"
print(f"{num}是{parity}") # 7是奇数
# 2. 默认值设置
name = input("输入名字: ") or "匿名"
# 等价于: name = input("输入名字: ") if input("输入名字: ") else "匿名"
# 3. 列表元素处理
scores = [85, 62, 90, 45, 78]
grades = ["优秀" if s >= 90 else "良好" if s >= 80 else "及格" if s >= 60 else "不及格"
for s in scores]
print(grades) # ['良好', '及格', '优秀', '不及格', '及格']
特殊情况处理
# 空值检查
value = None
result = value or "默认值"
# 嵌套三元(但建议拆分为函数)
def get_grade(score):
return ("A" if score >= 90 else
"B" if score >= 80 else
"C" if score >= 70 else
"D")
性能对比
import timeit
# 三元运算通常更快
n = 1000000
def test_if():
for i in range(n):
if i > 500000:
x = i
else:
x = 0
def test_ternary():
for i in range(n):
x = i if i > 500000 else 0
print(timeit.timeit(test_if, number=1)) # 约 0.12秒
print(timeit.timeit(test_ternary, number=1)) # 约 0.10秒
注意事项
- 可读性优先:嵌套超过2层时,建议用普通if-elif-else
- 性能优势:简单条件下三元运算比if-else快约15-20%
- 返回类型:两边返回类型尽量一致,避免调试困难
# 反例:类型不一致 x = 1 result = "高" if x > 5 else 0 # type: str | int,不建议 # 建议写法 result = "高" if x > 5 else "低" # type: str
三元运算适合简单判断,复杂逻辑请保持代码可读性优先。