如何在python中对许多嵌套列表中的项执行函数



我想在python中迭代大量嵌套列表,并递归地树到其他列表。该列表的一般格式为[[1, [2, [3, [4, 5]]]], [7, [8, [9, [10, 11]]]]]。例如,我想创建另一个嵌套列表,而不使大列表变平。

期望输出:[[1, [2, [3, [4, [5, x]]]]], [7, [8, [9, [10, [11, y]]]]]]

我已经尝试了函数递归,并使函数getChildren():

def getChildren(list):
for item in list:
item = [item, item + 1]
return list

我相信我已经很接近了。我想这样做很多次,直到一个值在底部。到目前为止,我的代码如下:

while True:
layer = []
for item in list: 
item = getChildren(item)
layer.append(item)
list.append(layer)

但是它没有像预期的那样工作。任何帮助吗?

尝试:

L = [[1, [2, [3, [4, 5]]]], [7, [8, [9, [10, 11]]]]]
def getChildren(L):
for indx, value in enumerate(L):
if isinstance(value, list):
getChildren(value)
else:
L[indx] = [value, value + 1]
getChildren(L)
print(L)

给:

[[[1, 2], [[2, 3], [[3, 4], [[4, 5], [5, 6]]]]], [[7, 8], [[8, 9], [[9, 10], [[10, 11], [11, 12]]]]]]

L = [[1, [2, [3, [4, 5]]]], [7, [8, [9, [10, 11]]]]]
def getChildren(L):
if isinstance(L[1], list): 
getChildren(L[1])
else:
L[1] = [ L[1], L[1]+1 ]
getChildren(L[0])
getChildren(L[1])
print(L)

给了:

[[1, [2, [3, [4, [5, 6]]]]], [7, [8, [9, [10, [11, 12]]]]]]
[[1, [2, [3, [4, [5, [6, 7]]]]]], [7, [8, [9, [10, [11, [12, 13]]]]]]]
[[1, [2, [3, [4, [5, [6, [7, 8]]]]]]], [7, [8, [9, [10, [11, [12, [13, 14]]]]]]]]

最新更新