gpt4 book ai didi

python - 添加到嵌套列表

转载 作者:行者123 更新时间:2023-12-05 04:22:05 25 4
gpt4 key购买 nike

我想将具有下一个值的元素添加到最嵌套的列表中,i。即.

列表

list_in = [2, 3, [4, 5, [6, 7], 6], 2, [5, 6]]

程序应该返回

list_out = [2, 3, [4, 5, [6, 7, 8], 6], 2, [5, 6]]

如果有 e。 X。两个相等的巢,我想得到:

list_in = [2, [4], [3]]

list_out = [2, [4, 5], [3, 4]]

怎么做?

最佳答案

递归解决方案:

list_in = [2, 3, [4, 5, [6, 7], 6], 2, [5, 6]]


def get_depths(lst, depths, current_depth=0):
out = [
get_depths(v, depths, current_depth + 1) if isinstance(v, list) else v
for v in lst
]
depths.setdefault(current_depth, []).append(out)
return out


depths = {}
list_out = get_depths(list_in, depths)
for lst in depths[max(depths)]:
lst.append(lst[-1] + 1)

print(list_out)

打印:

[2, 3, [4, 5, [6, 7, 8], 6], 2, [5, 6]]

对于 list_in = [2, [4], [3]] 它打印:

[2, [4, 5], [3, 4]]

关于python - 添加到嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74075793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com