← 中文资源

简体中文版本

pairwise 构建相邻滑动窗口

itertools.pairwise 把序列变成相邻对:差分、峰值步进直接落在窗口上;tee 复制迭代器错位一档、starmap 把每对解包成两参调用。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

deltas  : [0.5, -0.2, 1.3, -0.4, 1.3]
steepest: (21.8, 23.1)
pairs   : [(21.5, 22.0), (22.0, 21.8), (21.8, 23.1), (23.1, 22.7), (22.7, 24.0)]
falls   : [False, True, False, True, False]

实现说明

各个操作都建立在顶层绑定之上:temps、deltas、steepest、pairs。

使用要点

  • 跑完文件,输出里会留下标记——steepest:。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 跨调用保留的状态放在这些顶层绑定里:temps、deltas、steepest。

代码示例

from itertools import pairwise, tee, starmap

temps = [21.5, 22.0, 21.8, 23.1, 22.7, 24.0]

# pairwise 产出相邻对:固定宽度 2 的滑动窗口
deltas = [round(b - a, 1) for a, b in pairwise(temps)]
print('deltas  :', deltas)

# 最陡上升的一步:max + key 直接落在相邻对上
steepest = max(pairwise(temps), key=lambda pair: pair[1] - pair[0])
print('steepest:', steepest)

# tee 复制迭代器:一份保持原序,一份从第二个元素开始
current, lagged = tee(temps, 2)
next(lagged, None)
pairs = list(zip(current, lagged))
print('pairs   :', pairs)

# starmap 把每对解包成两参函数调用:判断温度是否下降
falls = list(starmap(lambda a, b: a > b, pairwise(temps)))
print('falls   :', falls)