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

如何将Python列表按数字标识分割为嵌套列表?

将扁平列表转换为分组嵌套列表

我想把以下Python列表:

list = [
    '1',
    'China',
    'hello',
    '2',
    'India',
    '3',
    'America',
    'Texas',
    'Cowboy'
]

转换为如下结构的嵌套列表:

newlist = [
    ['1', 'China', 'hello'], 
    ['2', 'India'], 
    ['3', 'America', 'Texas', 'Cowboy']
]

我自己写出了解决代码:

list = [
    '1',
    'China',
    'hello',
    '2',
    'India',
    '3',
    'America',
    'Texas',
    'Cowboy'
]

newlist = []
a = 1
n = 0

for i in list:
    rltvList = list[n]
    
    if str(a) == rltvList:
        temporaryList = []
        a += 1
        newlist.append(temporaryList)
        
    temporaryList.append(rltvList)
    n += 1

作为初学者,代码写法比较粗糙,还请见谅。

在编写代码前我先梳理了伪代码逻辑:

  1. 遍历目标列表;
  2. 若列表当前元素等于'1',则将其添加到临时列表;
  3. 持续向临时列表添加元素,直到列表当前元素等于'2';
  4. 将临时列表添加到新列表;
  5. 清空临时列表;
  6. 重复上述步骤直至遍历完整个列表。

需要说明的是,我们需要temporaryList来生成嵌套列表,没有它的话只能得到一个普通列表,无法实现分组嵌套的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:48:05