You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中将序列拆分为连续相邻二元组的最优雅实现方法

优化方案1:使用zip实现极简版(仅适用于窗口长度为2的场景)

这是最简洁的Python原生实现,利用zip的特性直接拼接原列表和偏移1位的列表即可完成配对:

lst = list(range(10))
# 得到元素为元组的结果
res = list(zip(lst, lst[1:]))
# 如果需要子元素为列表,再加一层转换
res = [list(pair) for pair in zip(lst, lst[1:])]

运行输出和你原有代码完全一致:[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]

优化方案2:通用滑窗实现(支持任意窗口长度)

如果后续需要调整窗口长度(比如要拆成3个元素的连续组),可以写一个通用的滑窗函数,扩展性更强:

def sliding_window(lst, window_size):
    return [lst[i:i+window_size] for i in range(len(lst) - window_size + 1)]

lst = list(range(10))
res = sliding_window(lst, 2)

如果窗口长度固定为2,直接用列表推导式一行就能写完:

res = [lst[i:i+2] for i in range(len(lst)-1)]

内容的提问来源于stack exchange,提问作者Shaun Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:18:02