将一个列表的嵌套形状应用到另一个平面列表上

Mar*_*tin 6 python arrays algorithm nested list

我有两个清单:

A:[[0, 1], [2, [3]], 4]

乙:[5, 6, 7, 8, 9]

我希望列表 B 可以与列表 A 具有相同的形状: [5, 6, 7, 8, 9]=>[[5, 6], [7, [8]], 9]

因此列表 A 和列表 B 具有相同的维度/形状:

A:[[0, 1], [2, [3]], 4]

乙:[[5, 6], [7, [8]], 9]

考虑一下时间复杂度,如果可能的话,希望有一种O(n)的方法。

moz*_*way 6

假设项目数量相同,您可以使用递归函数和迭代器:

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)推广到其他可迭代对象(迭代器除外)。


Dan*_*ejo 6

@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).