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

如何基于内部元素值拆分Python中的元组列表

实现方案

最符合Python风格的写法是使用标准库itertools.groupby,它原生支持按指定key对连续的同组元素进行分组,刚好匹配你「元组索引1的值变化时拆分列表」的需求:

import itertools

# 原元组列表
data = [
    ('All', 1, 0.6, 5.0),
    ('right,', 1, 0.6, 5.0),
    ("let's", 1, 0.6, 5.0),
    ('get', 0, 0.36, 5.0),
    ('the', 0, 0.36, 5.0),
    ('clock', 0, 0.36, 5.0),
    ('up', 0, 0.36, 5.0), 
    ('here.', 0, 0.36, 5.0)
]

# 按元组索引1的元素分组,直接生成拆分后的子列表
result = [list(group) for _, group in itertools.groupby(data, key=lambda x: x[1])]

运行后result就是你需要的输出:

[
    [('All', 1, 0.6, 5.0), ('right,', 1, 0.6, 5.0), ("let's", 1, 0.6, 5.0)],
    [('get', 0, 0.36, 5.0), ('the', 0, 0.36, 5.0), ('clock', 0, 0.36, 5.0), ('up', 0, 0.36, 5.0), ('here.', 0, 0.36, 5.0)]
]

如果你的场景确定只会发生一次值变化,只需要拆成两个列表,也可以用切片写法,性能略高:

# 找到第一个值变化的索引
split_pos = next(idx for idx, item in enumerate(data[1:], 1) if item[1] != data[0][1])
part1, part2 = data[:split_pos], data[split_pos:]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:06:04