一、列表操作技巧
- 列表推导式
# 传统循环
squares = []
for x in range(10):
squares.append(x**2)
# 列表推导式(更简洁)
squares = [x**2 for x in range(10)]
- 使用map和filter
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x*2, nums)) # [2, 4, 6, 8]
evens = list(filter(lambda x: x%2 == 0, nums)) # [2, 4]
- 合并列表
a = [1, 2]
b = [3, 4]
combined = a + b # [1, 2, 3, 4]
a.extend(b) # 直接扩展a
二、字典操作技巧
- 合并字典
d1 = {'a': 1}
d2 = {'b': 2}
merged = {**d1, **d2} # Python 3.5+
merged = d1 | d2 # Python 3.9+
- 字典推导式
squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, ...}
- 默认值处理
from collections import defaultdict
d = defaultdict(int) # 访问不存在的键时返回0
d['count'] += 1 # 自动初始化为0
三、字符串处理
- f-string格式化(Python 3.6+)
name = "Alice"
print(f"Hello, {name}!") # 直接嵌入变量
print(f"{3.14159:.2f}") # 保留两位小数 → 3.14
- 拆分与连接
s = "a,b,c"
parts = s.split(",") # ['a', 'b', 'c']
joined = "-".join(parts) # 'a-b-c'
- 快速去空格
s = " text "
stripped = s.strip() # "text"
四、函数与Lambda
- 默认参数与可变参数
def greet(name, message="Hi"):
print(f"{message}, {name}!")
def sum_all(*args):
return sum(args)
- Lambda表达式
add = lambda x, y: x + y
sorted_names = sorted(names, key=lambda x: x.lower())
五、文件操作
- 使用with自动关闭文件
with open("file.txt", "r") as f:
content = f.read() # 无需手动调用f.close()
- 逐行读取大文件
with open("large_file.txt") as f:
for line in f: # 内存高效
process(line)
六、代码优化
- 生成器节省内存
def gen_numbers(n):
for i in range(n):
yield i # 惰性计算,适合大数据
- 使用enumerate获取索引
for index, value in enumerate(['a', 'b', 'c']):
print(index, value) # 0 a, 1 b, 2 c
- 用zip并行迭代
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
七、错误处理
- try-except捕获异常
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
- 自定义异常
class MyError(Exception):
pass
八、模块与库
- 常用内置库
- collections:提供deque, Counter等高效数据结构
- itertools:迭代工具(排列组合、无限迭代器等)
- os/shutil:文件和目录操作
- 快速HTTP请求
import requests
response = requests.get("https://api.example.com/data")
print(response.json())
九、其他实用技巧
- 交换变量值
a, b = 1, 2
a, b = b, a # a=2, b=1
- 条件表达式
max_val = x if x > y else y
- 链式比较
if 0 < x < 10: # 等价于 0 < x and x < 10
print("Valid")