本文整合了 Python 编程中的常用技巧和代码片段。

defaultdict 用法

传统方式

1
2
3
4
5
6
7
8
9
10
11
12
13
# 方式一: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

推荐方式

1
2
3
4
5
6
7
8
from collections import defaultdict

# 使用 defaultdict
foo = defaultdict(int)
foo[key] += 1

# 使用 get 方法
foo[key] = foo.get(key, 0) + 1

嵌套 defaultdict

1
2
3
4
5
from collections import defaultdict

# 两层嵌套
nested = defaultdict(lambda: defaultdict(int))
nested['a']['b'] += 1

大文件 JSON 处理

使用 ijson 流式解析大型 JSON 文件:

1
2
3
4
5
6
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)

装饰器

基本装饰器

1
2
3
4
5
6
7
8
9
10
11
12
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!')

带参数的装饰器

1
2
3
4
5
6
7
8
9
10
11
12
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 时间戳

1
2
3
4
5
from datetime import datetime, timezone

dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp) # 1445212800.0

获取 UTC 时间

1
2
3
from datetime import timezone

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

文件操作

文件操作模式

模式 说明
'r' 读取文本
'w' 写入文本
'a' 追加文本
'rb' 读取二进制
'wb' 写入二进制

追加写入

1
2
with open("test.txt", "a") as f:
f.write("appended text")

获取当前文件目录

1
2
3
4
5
6
7
8
9
10
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 命令

1
2
3
4
5
6
7
import subprocess
import sys

cmd = 'ls -l'
retcode = subprocess.call(cmd, shell=True)
if retcode != 0:
sys.exit(retcode)

获取对象大小

1
2
import sys
size = sys.getsizeof(obj)

二维数组列求和

1
2
3
my_list = [[1, 2, 3], [4, 5, 6]]
col_totals = [sum(x) for x in zip(*my_list)]
# [5, 7, 9]

参考链接