python - 列表到混合维度矩阵

标签 python arrays python-3.x list numpy

我一直在试图弄清楚如何获取一个列表并匹配任何矩阵的形状。

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/

相关文章:

python - 如何在 python 中将 pandas.qcut 作为 sqlalchemy 查询的一部分应用?

python - 如何在 PyCharm 社区版中查看使用 DataFrame 绘制的图表?

c++ - 以整数数组为参数并返回数组中奇数之和的函数

python - 通过 post 请求将二进制数据作为文件提交

mysql - Python3 从 MySQL 比较中提取日期无法正常工作

python-3.x - 使用单词列表中的最小单词子串形成目标字符串

python - 使用.format和变量的python字符串格式化

python - Lexing Python 资源

java - 修复了保持数据正确组织而不重复的问题

arrays - 关于懒惰 [ RAKU ]