itertools.pairwise Walks Adjacent Pairs
Walk adjacent pairs with itertools.pairwise: compute deltas between consecutive prices, flag threshold jumps, and close rings by re-appending the first item.
Code
from itertools import pairwise
# pairwise 把序列切成相邻对:滑窗大小恒为 2(3.10+ 内置)
prices = [42, 45, 44, 48, 47]
deltas = [b - a for a, b in pairwise(prices)]
print("day deltas:", deltas)
# 相邻比较的典型用法:找出跳变超过阈值的相邻对
jumps = [(a, b) for a, b in pairwise(prices) if abs(b - a) >= 3]
print("jumps:", jumps)
# 字符串也是序列:相邻字符成对
print("char pairs:", list(pairwise("abcf")))
# 环形比较:把首元素重新接回序列末尾
ring = [3, 1, 4, 1, 5]
gaps = [abs(b - a) for a, b in pairwise(ring + ring[:1])]
print("ring gaps:", gaps)Output
Captured from a sandboxed run of this snippet in the build pipeline.
day deltas: [3, -1, 4, -1]
jumps: [(42, 45), (44, 48)]
char pairs: [('a', 'b'), ('b', 'c'), ('c', 'f')]
ring gaps: [2, 3, 3, 4, 2]What to watch for
- Built-in APIs only, so there is no supply chain to vet.
pairwise slides a fixed window of 2 over the input, yielding overlapping (current, next) tuples one step at a time — a sequence of n items produces n−1 pairs, and an input shorter than 2 yields nothing at all.
The line doing the real work:
jumps = [(a, b) for a, b in pairwise(prices) if abs(b - a) >= 3]
The pairs feed a filter: only adjacent price moves of 3 or more survive, so (42, 45) and (44, 48) make the cut while the two −1 dips do not.
The mechanism needs a second piece:
gaps = [abs(b - a) for a, b in pairwise(ring + ring[:1])]
ring + ring[:1] re-appends the first element to the end, so the final pair (5, 3) closes the loop — the standard trick for circular adjacency with pairwise.
Rounding out the trio, this line:
deltas = [b - a for a, b in pairwise(prices)]
computes day-over-day deltas straight from the pairs. Because pairwise accepts any iterable, pairwise("abcf") pairs adjacent characters the same way.
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. Every import resolves inside the standard library — `itertools`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.