我想將具有下一個值的元素添加到最嵌套的串列中,即
對于串列
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]]
如果有兩個相等的巢,我想得到:
list_in = [2, [4], [3]]
list_out = [2, [4, 5], [3, 4]]
怎么做?
uj5u.com熱心網友回復:
遞回解決方案:
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]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515914.html
標籤:Python列表嵌套的
上一篇:如何使用串列創建具有多個值的字典
