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

如何将含分类标识的单个列表转换为带序号的嵌套子列表?

如何将扁平列表按前缀分组并生成带序号的嵌套子列表

问题背景

给定如下扁平列表:

my_list = ['a_norm', 'a_std', 'a_min', 'a_max', 'a_flag', 'b_norm', 'b_std', 'b_min', 'b_max', 'b_flag', 'c_norm', 'c_std', 'c_min', 'c_max', 'c_flag']

需要按前缀(a_/b_/c_)分组,生成带序号的嵌套子列表且保留原有顺序,期望输出:

a_list = [[1, "a_norm"], [2, "a_std"], [3, "a_min"], [4, "a_max"], [5, "a_flag"]]
b_list = [[1, "b_norm"], [2, "b_std"], [3, "b_min"], [4, "b_max"], [5, "b_flag"]]
c_list = [[1, "c_norm"], [2, "c_std"], [3, "c_min"], [4, "c_max"], [5, "c_flag"]]

用户尝试的代码陷入死循环且逻辑错误,代码如下:

a_list = []
b_list = []
c_list = []
i = 1
j = 1
k = 1
while (i < 6) and (j < 6) and (k < 6):
    for item in my_list:
        if 'a' in item:
            a_list.append(i)
            a_list.append(item)
            i + 1
        elif 'b' in my_list:
            b_list.append(j)
            b_list.append(item)
            j + 1
        elif 'c' in my_list:
            c_list.append(k)
            c_list.append(item)
            k + 1

错误原因分析

  • 死循环:i + 1仅做计算未赋值给i(需改为i += 1),同时while嵌套for循环会反复遍历整个列表,导致序号永远无法达到终止条件。
  • 结构错误:直接追加序号和元素会得到扁平列表,而非要求的嵌套子列表(需追加[i, item])。
  • 判断错误:elif 'b' in my_list是检查整个列表是否含'b',而非当前元素是否含'b',应改为'b' in item。

正确实现方法

方法1:直接遍历分组(简单直观)

my_list = ['a_norm', 'a_std', 'a_min', 'a_max', 'a_flag', 'b_norm', 'b_std', 'b_min', 'b_max', 'b_flag', 'c_norm', 'c_std', 'c_min', 'c_max', 'c_flag']

a_list = []
b_list = []
c_list = []

# 为每个分组维护独立序号
a_idx = 1
b_idx = 1
c_idx = 1

for item in my_list:
    if item.startswith('a_'):
        a_list.append([a_idx, item])
        a_idx += 1
    elif item.startswith('b_'):
        b_list.append([b_idx, item])
        b_idx += 1
    elif item.startswith('c_'):
        c_list.append([c_idx, item])
        c_idx += 1

# 输出结果
print("a_list =", a_list)
print("b_list =", b_list)
print("c_list =", c_list)

方法2:字典分组(支持扩展更多前缀)

如果后续可能新增d_/e_等前缀,用字典分组更灵活,无需单独定义每个列表:

my_list = ['a_norm', 'a_std', 'a_min', 'a_max', 'a_flag', 'b_norm', 'b_std', 'b_min', 'b_max', 'b_flag', 'c_norm', 'c_std', 'c_min', 'c_max', 'c_flag']

# 初始化分组字典,存储每个前缀对应的列表和当前序号
groups = {
    'a': {'list': [], 'idx': 1},
    'b': {'list': [], 'idx': 1},
    'c': {'list': [], 'idx': 1}
}

for item in my_list:
    # 提取下划线前的前缀
    prefix = item.split('_')[0]
    if prefix in groups:
        groups[prefix]['list'].append([groups[prefix]['idx'], item])
        groups[prefix]['idx'] += 1

# 提取最终结果
a_list = groups['a']['list']
b_list = groups['b']['list']
c_list = groups['c']['list']

# 输出结果
print("a_list =", a_list)
print("b_list =", b_list)
print("c_list =", c_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 00:00:56