pairwise Builds Adjacent Sliding Windows

Turn a series into adjacent pairs with itertools.pairwise, then feed deltas, peak steps, tee branching, and starmap calls from those windows.

PythonData Integrity

Code

pythonsnippet
21 lines
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)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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]

How the snippet works

Module-level bindings hold the data — temps, deltas, steepest, pairs — with no function scope in between.

Applying it

Output lines are prefixed (deltas :, steepest:, pairs :), making each step’s effect easy to spot.

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `temps`, `deltas`, `steepest`.