本文目录导读:
- 列表推导式 vs 传统循环
- 字典推导式
- 简化条件赋值
- 优雅处理文件
- 智能解包
- 集合操作简化去重
- 使用装饰器简化重复代码
- f-string 格式化
- any() 和 all() 简化条件判断
- 链式比较
- 使用enumerate获取索引
- 使用zip并行迭代
我将为您展示一些Python优雅写法的实际案例,这些技巧能显著提升代码质量和开发效率。
列表推导式 vs 传统循环
传统写法
# 找出所有偶数并平方
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = []
for num in numbers:
if num % 2 == 0:
result.append(num ** 2)
优雅写法
# 一行搞定,更简洁、更Pythonic result = [num ** 2 for num in numbers if num % 2 == 0] # 输出: [4, 16, 36, 64]
字典推导式
实际场景:处理API返回数据
# 假设从API获取用户数据
users = [
{"id": 1, "name": "Alice", "age": 25},
{"id": 2, "name": "Bob", "age": 30},
{"id": 3, "name": "Charlie", "age": 35}
]
# 优雅写法:创建id到name的映射
user_map = {user["id"]: user["name"] for user in users}
# 输出: {1: 'Alice', 2: 'Bob', 3: 'Charlie'}
简化条件赋值
传统写法
score = 85
if score >= 60:
result = "通过"
else:
result = "未通过"
优雅写法
# 使用三元表达式 result = "通过" if score >= 60 else "未通过"
优雅处理文件
传统写法
f = open('data.txt', 'r')
try:
data = f.read()
finally:
f.close()
优雅写法
# 使用with语句,自动处理资源释放
with open('data.txt', 'r') as f:
data = f.read()
智能解包
实际场景:分割数据
# 解包列表
name, age, *others = ["Alice", 25, "Engineer", "New York"]
print(name) # Alice
print(age) # 25
print(others) # ['Engineer', 'New York']
# 字典解包合并
config1 = {"host": "localhost", "port": 8080}
config2 = {"debug": True, "port": 9090} # 后者会覆盖前者重复键
merged = {**config1, **config2}
# 输出: {'host': 'localhost', 'port': 9090, 'debug': True}
集合操作简化去重
# 实际场景:找出两个列表的共同元素
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# 传统写法
common = []
for i in list1:
if i in list2:
common.append(i)
# 优雅写法
common = list(set(list1) & set(list2)) # [4, 5]
使用装饰器简化重复代码
实际场景:函数执行时间统计
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} 执行时间: {time.time() - start:.2f}秒")
return result
return wrapper
@timer
def process_data():
# 模拟复杂计算
time.sleep(1)
return "完成"
# 调用时自动计时
process_data()
f-string 格式化
传统写法
name = "Alice"
age = 25
message = "Hello, {}! You are {} years old.".format(name, age)
优雅写法
# Python 3.6+ 推荐
message = f"Hello, {name}! You are {age} years old."
# 支持表达式
message = f"Hello, {name.upper()}! You are {age + 5} years old."
any() 和 all() 简化条件判断
# 实际场景:检查数据完整性
data = [True, True, False, True]
readings = [20, 25, 18, 12, 30]
# 是否至少有一个True
has_valid = any(data)
# 是否所有值都大于10
all_valid = all(r > 10 for r in readings)
# 代替传统循环
all_valid = True
for r in readings:
if r <= 10:
all_valid = False
break
链式比较
# 传统写法
x = 5
if x > 3 and x < 10:
print("在范围内")
# 优雅写法
if 3 < x < 10:
print("在范围内")
使用enumerate获取索引
# 传统写法
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
# 优雅写法
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
使用zip并行迭代
# 同时遍历多个列表
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
grades = ["A", "A+", "B+"]
for name, score, grade in zip(names, scores, grades):
print(f"{name}: {score}分, 等级{grade}")
这些优雅写法不仅让代码更简洁,还能提高可读性和维护性,代码是写给人看的,优雅的代码更容易被理解和维护。
标签: 优雅写法