实现说明
各个操作都建立在顶层绑定之上: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)