Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将元素插入到空列表的任意深度嵌套列表中_Python_List_Nested - Fatal编程技术网

Python 如何将元素插入到空列表的任意深度嵌套列表中

Python 如何将元素插入到空列表的任意深度嵌套列表中,python,list,nested,Python,List,Nested,在任意深度嵌套的空列表中,我想插入列表列表中的元素。两个列表的长度相同 例如,我可能想插入 a = [ [1], [2,3], [[4,5]] ] 进入 以便我获得 c = [ [[1]], [[[[2,3]]]], [ [4,5] ] ]. 我已经尝试了各种方法,但还没有找到可行的解决方案。您可以使用递归: a = [ [1], [2,3], [[4,5]] ] b = [ [[ ]], [[[[ ]]]], [ ] ] def update(j, k): return nex

在任意深度嵌套的空列表中,我想插入列表列表中的元素。两个列表的长度相同

例如,我可能想插入

a = [ [1], [2,3], [[4,5]] ]
进入

以便我获得

c =  [ [[1]], [[[[2,3]]]], [ [4,5] ] ]. 
我已经尝试了各种方法,但还没有找到可行的解决方案。

您可以使用递归:

a = [ [1], [2,3], [[4,5]] ]
b =  [ [[ ]], [[[[ ]]]], [ ] ]
def update(j, k):
   return next(k) if not j else [update(i, k) for i in j]

print(update(b, iter(a)))
输出:

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

对于
b
的每个子列表,您可以迭代地将内部子列表分配给相同的变量,直到子列表变为空,此时您可以将
a
中的相应子列表复制到空子列表中:

for s, l in zip(a, b):
    while l:
        l, =  l
    l[:] = s
使
b
变为:

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