假设项目数量相同,您可以使用递归函数和迭代器:
A = [[0, 1], [2, [3]], 4]
B = [5, 6, 7, 8, 9]
def copy_shape(l, other):
if isinstance(other, list):
other = iter(other)
if isinstance(l, list):
return [copy_shape(x, other) for x in l]
else:
return next(other)
out = copy_shape(A, B)
Run Code Online (Sandbox Code Playgroud)
输出:[[5, 6], [7, [8]], 9]
注意。复杂度为O(n)。您还可以使用if hasattr(other, '__len__')或if not hasattr(other, '__next__')代替 来if isinstance(other, list)推广到其他可迭代对象(迭代器除外)。
@Mozway 想法的单行变体,使用列表理解:
A = [[0, 1], [2, [3]], 4]
B = [5, 6, 7, 8, 9]
def un_flatten(t, d):
return [un_flatten(e, d) if isinstance(e, list) else next(d) for e in t]
match = un_flatten(A, iter(B))
print(match)
Run Code Online (Sandbox Code Playgroud)
输出
[[5, 6], [7, [8]], 9]
Run Code Online (Sandbox Code Playgroud)
请注意,它需要将列表转换B为迭代器。复杂度是O(n).