在Python中递归地修改嵌套列表



我有一个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]]

试试:

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 ',真],"4",[[没错,‘10’,' 11 '],真正]]

最新更新