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

如何让Python函数自动遍历嵌套列表并批量应用strip方法?

处理嵌套列表的字符串清理函数

问题背景

需要实现一个Python函数,接收嵌套列表作为输入,自动遍历所有子列表,对每个字符串元素应用strip()方法去除首尾空白字符,最终返回清理后的嵌套列表。目前已有clean_one函数仅能处理单个子列表,需扩展其功能或编写新函数实现批量处理。

示例输入(嵌套列表片段):

tringles_new[:15]

[['49', 'XT', '19.0', '93 \n'],
 ['YTX', '124.0', '167 ', '77.0\n'],
 ['4 ', 'Y', '128,', '125,\n'],
 ['142.0', '120', '141.0\n'],
 ['12 ', '51.0\n'],
 ['0,', ' 82', '156\n'],
 ['82', '102.0\n'],
 ['94', 'YYZ', '178.0', '72\n'],
 [' 120', 'YXT', '142', ' 134\n'],
 ['45,', '46', '79.0\n'],
 [' 114', 'YT', '155.0', '168\n'],
 ['98,', '27,', '119.0\n'],
 ['61,', 'XYY', '33', '1\n'],
 ['ZY', '103', '123.0', '76\n'],
 ['YZZ', '52', ' 17', ' 92\n']]

现有单个子列表处理函数:

def clean_one(i):
    clean_one_output = []
    for j in i:
        j = j.strip()
        clean_one_output.append(j)
    return clean_one_output

解决方案

方案1:基于现有函数扩展批量处理

利用已有的clean_one函数,编写新函数遍历嵌套列表的每个子列表,逐一处理后收集结果:

def clean_nested_list(nested_list):
    cleaned_result = []
    for sublist in nested_list:
        cleaned_result.append(clean_one(sublist))
    return cleaned_result

使用示例:

cleaned_tringles = clean_nested_list(tringles_new)

方案2:修改原函数支持嵌套列表

直接修改clean_one,使其能自动识别输入是否为列表,递归处理嵌套结构:

def clean_one(item):
    # 若输入是列表,遍历每个元素递归处理
    if isinstance(item, list):
        cleaned_sublist = []
        for elem in item:
            cleaned_sublist.append(clean_one(elem))
        return cleaned_sublist
    # 若输入是字符串,执行strip操作
    elif isinstance(item, str):
        return item.strip()
    # 非字符串非列表的元素,直接返回原内容
    else:
        return item

使用示例:

cleaned_tringles = clean_one(tringles_new)

方案3:列表推导式简化实现

如果不需要保留原clean_one函数,可直接用双层列表推导式一步完成清理:

def clean_nested_list(nested_list):
    return [[elem.strip() for elem in sublist] for sublist in nested_list]

这种写法简洁高效,适合不需要额外扩展逻辑的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:10:47