首页 > 解决方案 > 我们可以制作md-matrix吗?

问题描述

  1. 用python制作md矩阵。
  2. reshape函数的原理是什么?

in 和 result 应该看起来像 result

 in = (0, 1, 2, 3, 4, 5, 6, 7, 8)
tensor = (2, 3, 2)
result:
(((0, 1), (2, 3), (4, 5)), ((6, 7), (8, 0), (0, 0)))

标签: python

解决方案


尝试:

def multiply (arr):
    result = 1
    for x in arr:
        result *= x
    return result

def reshape(shape, arr):
    result = arr
    newSize = multiply(shape)
    if (len(arr) < newSize):
        while (len(arr) < newSize):
            result.append(0)
    else:
        result= result[:newSize]

    for s in shape[::-1]:
        result = [ result[i:i+s] for i in range(0,len(result),s)]
    return result

data = [0, 1, 2, 3, 4, 5, 6, 7, 8]
shape = [2, 3, 2]

print(reshape(shape, data))

data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 
shape = [6, 2]

print(reshape(shape, data))


推荐阅读