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

Python实现列表中按起始相同子串顺序分组字符串

按相邻元素起始子串顺序分组列表元素

问题场景

给定如下字符串列表:

my_list = ["A-Item one", "B-Item two", "A-Item three", "A-Item four", "B-Item five", "B-Item six"]

需要对列表元素进行连续相邻分组:当相邻元素的起始子串(即-分隔的第一部分)相同时归为同一组;遇到起始子串与前一个元素不同时,创建新组。最终期望输出:

grouped_items = [["A-Item one"], ["B-Item two"], ["A-Item three", "A-Item four"], ["B-Item five", "B-Item six"]]

解决方案

方法一:使用标准库itertools.groupby

itertools.groupby的核心特性就是对连续的相同键元素进行分组,完全匹配需求,实现起来简洁高效。

from itertools import groupby

my_list = ["A-Item one", "B-Item two", "A-Item three", "A-Item four", "B-Item five", "B-Item six"]

# 提取每个元素的起始子串作为分组键
def get_group_key(item):
    return item.split("-")[0]

# 分组并转换为目标格式
grouped_items = [list(group) for _, group in groupby(my_list, key=get_group_key)]

print(grouped_items)

方法二:基础循环实现

如果不想依赖标准库,也可以用基础循环手动实现分组逻辑,更直观易懂:

my_list = ["A-Item one", "B-Item two", "A-Item three", "A-Item four", "B-Item five", "B-Item six"]

if not my_list:
    grouped_items = []
else:
    grouped_items = []
    current_group = [my_list[0]]
    current_key = my_list[0].split("-")[0]
    
    for item in my_list[1:]:
        item_key = item.split("-")[0]
        if item_key == current_key:
            current_group.append(item)
        else:
            grouped_items.append(current_group)
            current_group = [item]
            current_key = item_key
    # 加入最后一组
    grouped_items.append(current_group)

print(grouped_items)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:06:21