我有两份名单:
答:[[0, 1], [2, [3]], 4]
B:[5, 6, 7, 8, 9]
我希望列表B与列表A:[5, 6, 7, 8, 9] => [[5, 6], [7, [8]], 9]具有相同的形状
因此,表A和表B具有相同的尺寸/形状:
答:[[0, 1], [2, [3]], 4]
B:[[5, 6], [7, [8]], 9]
考虑到时间的复杂性,如果可能的话,我希望有一个O(n)的方法。
发布于 2022-07-20 09:56:57
假设项目数相同,则可以使用递归函数和迭代器:
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]
注意:复杂度为O(n)。您还可以使用if hasattr(other, '__len__')或if not hasattr(other, '__next__')代替if isinstance(other, list),将其概括为其他可迭代性(迭代器除外)。
发布于 2022-07-20 10:07:43
@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)输出
[[5, 6], [7, [8]], 9]注意,它需要将列表B转换为迭代器。复杂性是O(n)。
发布于 2022-07-20 10:41:44
这是另一种处理字符串和eval的方法-
a = [[0, 1], [2, [3]], 4]
b = [5, 6, 7, 8, 9]
s = ''
i = 0
for char in str(a):
if char.isdigit(): # or you can use re.match(r'\w+', char)
s += str(b[i])
i += 1
else:
s += char
out_b = eval(s)输出
[[5, 6], [7, [8]], 9]https://stackoverflow.com/questions/73049456
复制相似问题