在 Python 中以递归方式修改嵌套列表

Modify a nested list recursively in Python

提问人:NiSi 提问时间:12/19/2022 最后编辑:NiSi 更新时间:12/19/2022 访问量:107

问:

我有一个喜欢:nested liststring / list(str)

li = [["1", ["2", "3"]], "4", [[["5", "6", "7"], "10", "11"], ["12", "13", "14"]]]

我想要一个具有相同嵌套结构的列表作为输出,但所有满足条件的子列表:

  • len(sublist) in {2, 3}
  • 列表中的所有元素都是(请参阅函数<str>to_true)

必须替换为 . 预期输出应为True

[["1", True], "4", [[True, "10", "11"], True]]

我怎样才能写一个(可能是递归的)函数?
另一种可能的方法是在 .
deepcopy

def to_true(o) -> bool:
    # True if o is a 2/3 element list/tuple containing only <str>
    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)

>>> func(li)

[["1", True], "4", [[True, "10", "11"], True]]

Python 递归 嵌套列表

评论


答:

3赞 Vagner 12/19/2022 #1

试试看:

def my_func(my_list):
    result = []
    for i in my_list:
        if isinstance(i, list):
            # Recursively transform the sublist
            result.append(my_func(i))
        else:
            result.append(i)
    # Check if the result should be replaced with True
    if all(isinstance(i, str) for i in result) and len(result) in {2, 3}:
        return True
    return result

my_list = [["1", ["2", "3"]], "4", [[["5", "6", "7"], "10", "11"], ["12", "13", "14"]]]

print(my_func(my_list))

输出:

[['1', True], '4', [[True, '10', '11'], true]]