我有两个 list :
A: [[0, 1], [2, [3]], 4]
B: [5, 6, 7, 8, 9]
我希望列表B的形状与列表A相同:
因此,列表A和列表B具有相同的尺寸/形状:
A: [[0, 1], [2, [3]], 4]
B: [[5, 6], [7, [8]], 9]
考虑到时间复杂性,如果可能的话,我希望有一种O(n)的方法.
我有两个 list :
A: [[0, 1], [2, [3]], 4]
B: [5, 6, 7, 8, 9]
我希望列表B的形状与列表A相同:
因此,列表A和列表B具有相同的尺寸/形状:
A: [[0, 1], [2, [3]], 4]
B: [[5, 6], [7, [8]], 9]
考虑到时间复杂性,如果可能的话,我希望有一种O(n)的方法.
假设项数相同,可以使用递归函数和迭代器:
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)
输出:[[5, 6], [7, [8]], 9]
NB. the complexity is O(n). You can also use 100 or 101 in place of 102 to generalize to other iterables (except iterator).