如何用Python递归修改嵌套列表:替换符合条件子列表为True
问题
我有一个由字符串/字符串列表组成的嵌套列表,示例如下:
li = [["1", ["2", "3"]], "4", [[["5", "6", "7"], "10", "11"], ["12", "13", "14"]]]
我希望输出一个结构相同的列表,但所有满足以下条件的子列表需替换为True:
- 子列表的长度为2或3(即
len(sublist) in {2, 3}) - 列表中所有元素均为字符串类型(可参考给定的
to_true函数)
预期输出:
[["1", True], "4", [[True, "10", "11"], True]]
给定的to_true函数如下:
def to_true(o) -> bool: # 当o是包含仅字符串的2/3元素列表/元组时返回True if not isinstance(o, (list, tuple)): return False if len(o) not in {2, 3}: return False return all(isinstance(i, str) for i in o)
如何编写一个(可递归实现的)函数来完成该操作?也可以通过deepcopy后原地修改输入列表的方式实现。
解决方案
方式一:递归生成新列表
这种方式不修改原列表,通过递归遍历每个元素生成符合要求的新列表:
from typing import Union, List def transform_nested_list(lst: Union[List, str]) -> Union[List, str, bool]: # 先判断当前元素是否符合替换为True的条件 if to_true(lst): return True # 如果是列表,递归处理内部每个元素 if isinstance(lst, list): return [transform_nested_list(item) for item in lst] # 字符串直接返回 return lst
调用示例:
li = [["1", ["2", "3"]], "4", [[["5", "6", "7"], "10", "11"], ["12", "13", "14"]]] print(transform_nested_list(li)) # 输出: [["1", True], "4", [[True, "10", "11"], True]]
方式二:深拷贝后原地修改
如果需要保留原列表,可先深拷贝再递归修改新列表:
from copy import deepcopy from typing import Union, List def transform_in_place(lst: Union[List, str]) -> Union[List, str, bool]: # 判断是否需要替换为True if to_true(lst): return True if isinstance(lst, list): # 深拷贝原列表,避免修改原始数据 new_lst = deepcopy(lst) for i in range(len(new_lst)): new_lst[i] = transform_in_place(new_lst[i]) return new_lst return lst
调用示例:
li = [["1", ["2", "3"]], "4", [[["5", "6", "7"], "10", "11"], ["12", "13", "14"]]] result = transform_in_place(li) print(result) # 输出: [["1", True], "4", [[True, "10", "11"], True]]
代码说明
- 两种方案都依赖给定的
to_true函数判断是否替换子列表 - 递归核心逻辑:遍历元素,若为列表则递归处理内部元素;若符合
to_true条件则返回True;否则返回原元素(字符串) - 方式一逻辑简洁,直接生成新列表;方式二适合需要保留原列表的场景
内容的提问来源于stack exchange,提问作者NiSi
相关产品推荐
相关产品推荐

