1️⃣ 最原始:多行 if
if score >= 60:
result = "pass"
else:
result = "fail"
2️⃣ 三元表达式:一行搞定 ✍️
result = "pass" if score >= 60 else "fail"
模板:
值1 if 条件 else 值2
3️⃣ 嵌套套娃:两层是极限 🤏
level = (
"优秀" if score >= 90 else
"良好" if score >= 75 else
"及格" if score >= 60 else
"加油"
)
三层以上请写普通
if,否则** readability -100** 😅
4️⃣ 与 or/and 组合:赋默认值 🛠️
# 如果 name 为空串则用 "Guest"
user = name or "Guest"
# 如果 age>0 合法否则 0
valid_age = age if age > 0 else 0
5️⃣ 列表推导里狂飙:💎
# 把正数保留,负变 0
arr = [-3, 4, 7, -2]
out = [x if x > 0 else 0 for x in arr]
# [0, 4, 7, 0]
6️⃣ 字典花式取值:get 的语法糖 🍬
price = {"apple": 5, "banana": 3}
pay = price.get(fruit) if fruit in price else 0
7️⃣ 性能对比:与普通 if 几乎无差 ⚡️
import timeit
def ternary():
return "big" if 10 > 2 else "small"
def normal():
if 10 > 2:
return "big"
else:
return "small"
print(timeit.timeit(ternary)) # ≈ 0.05 s
print(timeit.timeit(normal)) # ≈ 0.05 s
结论:写三元不是为了快,是为了省行数 + 可读!
8️⃣ 不要踩的坑 ⚠️
| 坑 | 错误示范 | 正确 |
|---|---|---|
忘了 else | x = 1 if flag ❌ | x = 1 if flag else 0 ✅ |
| 低优先级 | 1 + x if flag else 0 实际 (1+x) if flag else 0 | 该加括号加括号 |
🏁 一句话口诀(背它!)
“值 A if 条件 else 值 B”
嵌套别过俩,括号要戴好,可读性优先👀