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

如何基于特定字符串将Python列表切割为嵌套列表?

按'remove'分隔符切割列表的实现方案

需求说明

给定一个列表,其中每组数据由用户名(必填)、可选的真实姓名组成,每组末尾都有固定的remove字符串作为分隔标记。需要将该列表切割为嵌套列表,每个子列表对应一组用户数据(包含1个或2个元素)。

原始输入列表:

list_of_people = ['jjo','josh','remove','flor30','florentina','remove','mary_h','remove','jasoncel3','jason celora','remove', 'lashit', 'remove']

预期输出结果:

cut_list = [ ['jjo','josh'], ['flor30', 'florentina'], ['mary_h'], ['jasoncel3', 'jason celora'], ['lashit']]

核心逻辑:以remove为分隔点,每次遇到remove时,收集上一个分隔点到当前位置之间的所有非remove元素,作为一个子列表存入结果。


现有尝试及问题

以下是尝试的代码及错误输出:

list_of_people = ['jjo','josh','remove','flor30','florentina','remove','mary_h','remove','jasoncel3','jason celora','remove', 'lashit', 'remove']

#Add the first 2 items
#If "remove" is there (means there was no real name), remove it
#Turn list into a list of lists
cut_list = list_of_people[0:2]

if "remove" in cut_list:
  cut_list.remove("remove")

cut_list = [cut_list]

#Loop through and cut based on the presence of "remove"
for i in range(2, len(list_of_people)):
  if list_of_people[i] == 'remove':
    first_back = list_of_people[i-1]
    if list_of_people.append(list_of_people[i-2]) != 'remove':
      second_back = list_of_people[i-2]
  
  cut_list.append([first_back, second_back])

print(cut_list)

错误输出:

[['jjo', 'josh'], ['josh', 'jjo'], ['josh', 'jjo'], ['josh', 'jjo'],
['florentina', 'flor30'], ['florentina', 'flor30'], ['mary_h',
'remove'], ['mary_h', 'remove'], ['mary_h', 'remove'], ['jason
celora', 'jasoncel3'], ['jason celora', 'jasoncel3'], ['lashit',
'remove']]

问题分析:

  • 硬编码取前2个元素的逻辑不通用,无法处理只有用户名的情况
  • 循环中错误使用list.append()(该方法返回None,不能用于判断)
  • 未正确记录上一个分隔点的位置,导致重复添加错误元素
  • 未处理仅含单个元素的分组(如mary_h、lashit)

正确实现方案

方法一:遍历收集法

通过维护临时列表收集当前组元素,遇到remove时将临时列表存入结果并清空,最后过滤空列表(避免末尾remove导致的空元素)。

list_of_people = ['jjo','josh','remove','flor30','florentina','remove','mary_h','remove','jasoncel3','jason celora','remove', 'lashit', 'remove']

cut_list = []
current_group = []

for item in list_of_people:
    if item == 'remove':
        # 遇到分隔符时,将非空当前组存入结果
        if current_group:
            cut_list.append(current_group)
            current_group = []
    else:
        # 非分隔符元素加入当前组
        current_group.append(item)

print(cut_list)

运行结果:

[['jjo', 'josh'], ['flor30', 'florentina'], ['mary_h'], ['jasoncel3', 'jason celora'], ['lashit']]

方法二:分割索引法

先找出所有remove的索引,再根据索引切片提取每组元素。

list_of_people = ['jjo','josh','remove','flor30','florentina','remove','mary_h','remove','jasoncel3','jason celora','remove', 'lashit', 'remove']

# 获取所有'remove'的位置索引
remove_indices = [i for i, val in enumerate(list_of_people) if val == 'remove']
cut_list = []
start = 0

for idx in remove_indices:
    # 提取从start到当前remove索引前的元素
    group = list_of_people[start:idx]
    if group:
        cut_list.append(group)
    start = idx + 1

print(cut_list)

运行结果与方法一一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:05:36