我一直在试图弄清楚如何获取一个列表并匹配任何矩阵的形状。
a = [1,2,3,4,5,6,7,8,9]
b = [[3],[[2]],[1,8,2],[[[7,3,2]]],[9]]
我希望列表 a 与矩阵 b 的维度相匹配。 a 和 b 都具有相同数量的单个元素。该函数要求 a 和 be 具有相同数量的元素。
output = [[1],[[2]],[3,4,5],[[[[6,7,8]],[9]]
我尝试这样做。
import numpy as np
lst = []
start = 0
def match_matrix(a,b):
for k, v in enumerate(b):
shape = np.shape(v)
lst.append(np.reshape(a[start:start+element_num], newshape= shape) # there problem is here, how would I figure out how many elements in any dimension matrix
start += element_num
return lst
最佳答案
不确定为什么要使用 numpy 来实现此目的。这是创建列表列表的简单解决方案
>>> a = [1,2,3,4,5,6,7,8,9]
>>> b = [[3],[[2]],[1,8,2],[[[7,3,2]]],[9]]
>>>
>>> def create_list(l, itr):
... return [create_list(e, itr) if isinstance(e, list) else next(itr) for e in l]
...
>>>
>>> create_list(b, iter(a))
[[1], [[2]], [3, 4, 5], [[[6, 7, 8]]], [9]]
关于python - 列表到混合维度矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52130913/