攒下来的小抄,多数是 itertools 和标准库里的边角料。
1. itertools.pairwise 取代手滑下标
from itertools import pairwise
for a, b in pairwise(rows):
if b['ts'] - a['ts'] > 60:
print('gap', a['id'], b['id'])2. collections.Counter 的算术
total = Counter(x) + Counter(y) # 并
only_a = (Counter(x) - Counter(y)) # 差3. str.removeprefix 而不是 [3:]
name = raw.removeprefix('user:')4. 一行读完整个文件再处理
with open(p, encoding='utf-8') as f:
lines = [ln.rstrip() for ln in f if ln.strip()]5. enumerate(start=1) 处理行号
其余 7 条(functools.cache、zip(*rows) 转置、dataclass(slots=True)、Path.glob 排序坑、typing.assert_never 穷尽检查、tempfile.NamedTemporaryFile(delete_on_close=False)、os.process_cpu_time_ns)另开一篇写。

评论 (0)