按自定义切片拆分数组:如何将连续同状态元组划分为嵌套子数组
连续相同状态元组分组方案
给定如下由状态标识和数值组成的元组数组:
source = [('active',1),('active',2),('active',3),('active',4), ('not active',7),('not active',5),('not active',6),('active',7),('active',8),('active',9)]
需要将连续具有相同状态标识的元组归为同一个子数组,最终输出结构如下:
[[('active',1),('active',2),('active',3), ('active',4)],[('not active',7),('not active',5),('not active',6)],[('active',7),('active',8),('active',9)]]
实现方案
方案1:使用Python标准库itertools.groupby(最简便)
groupby天然支持对连续出现的相同key的元素做分组,直接指定分组key为元组的第一个元素(状态标识)即可,代码如下:
from itertools import groupby source = [('active',1),('active',2),('active',3),('active',4), ('not active',7),('not active',5),('not active',6),('active',7),('active',8),('active',9)] result = [list(group) for key, group in groupby(source, key=lambda x: x[0])]
执行后result就是你需要的嵌套数组结构。
注意:
groupby只会把连续出现的相同key的元素分为一组,刚好匹配你的需求,不需要额外做排序操作(如果先排序会把所有相同状态的元素合并到一组,不符合保留连续分段的要求)。
方案2:手动遍历实现(无需导入依赖)
如果不想依赖itertools,可以自己写遍历逻辑,逐个判断当前元素的状态和上一个分组的状态是否一致即可:
source = [('active',1),('active',2),('active',3),('active',4), ('not active',7),('not active',5),('not active',6),('active',7),('active',8),('active',9)] result = [] current_group = [] current_status = None for item in source: status = item[0] if status != current_status: # 状态变化,保存上一个非空分组 if current_group: result.append(current_group) # 初始化新分组 current_group = [item] current_status = status else: # 状态一致,加入当前分组 current_group.append(item) # 把最后一个分组加入结果 if current_group: result.append(current_group)
两种方案运行后得到的结果完全一致,都能满足需求。
内容的提问来源于stack exchange,提问作者Igor Aldabaev
相关产品推荐
相关产品推荐

