Python 编程技巧集
本文整合了 Python 编程中的常用技巧和代码片段。
defaultdict 用法
传统方式
# 方式一:try-except
try:
result[key]
except KeyError:
result[key] = 0
finally:
result[key] += 1
# 方式二:判断存在
if key in foo:
foo[key] += 1
else:
foo[key] = 1
推荐方式
from collections import defaultdict
# 使用 defaultdict
foo = defaultdict(int)
foo[key] += 1
# 使用 get 方法
foo[key] = foo.get(key, 0) + 1
嵌套 defaultdict
from collections import defaultdict
# 两层嵌套
nested = defaultdict(lambda: defaultdict(int))
nested['a']['b'] += 1
大文件 JSON 处理
使用 ijson 流式解析大型 JSON 文件:
import ijson.backends.yajl2 as ijson
with open('large_file.json', 'rb') as f:
objects = ijson.items(f, 'item')
for obj in objects:
process(obj)
装饰器
基本装饰器
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f'call {func.__name__}()')
return func(*args, **kwargs)
return wrapper
@log
def hello():
print('Hello!')
带参数的装饰器
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f'{text} {func.__name__}()')
return func(*args, **kwargs)
return wrapper
return decorator
@log('DEBUG')
def hello():
print('Hello!')
时间处理
datetime 转 Unix 时间戳
from datetime import datetime, timezone
dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp) # 1445212800.0
获取 UTC 时间
from datetime import timezone
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
文件操作
文件操作模式
| 模式 | 说明 |
|---|---|
'r' | 读取文本 |
'w' | 写入文本 |
'a' | 追加文本 |
'rb' | 读取二进制 |
'wb' | 写入二进制 |
追加写入
with open("test.txt", "a") as f:
f.write("appended text")
获取当前文件目录
import os
# 方法一
dir_path = os.path.dirname(os.path.realpath(__file__))
# 方法二
dir_path = os.path.dirname(os.path.abspath(__file__))
# 构建文件路径
file_path = os.path.join(dir_path, 'output', 'data.csv')
其他技巧
运行 Shell 命令
import subprocess
import sys
cmd = 'ls -l'
retcode = subprocess.call(cmd, shell=True)
if retcode != 0:
sys.exit(retcode)
获取对象大小
import sys
size = sys.getsizeof(obj)
二维数组列求和
my_list = [[1, 2, 3], [4, 5, 6]]
col_totals = [sum(x) for x in zip(*my_list)]
# [5, 7, 9]