题目:
思路:
(1)遍历出矩阵中所有的元素
(2)使用切片的方法重新组成一个新的矩阵
代码:
import numpy as np
class Solution:
def matrixReshape(self, nums, r, c):
row = len(nums)
column = len(nums[0])
if row*column != r*c:
return nums
num = []
for i in nums:
for j in i:
num.append(j)
print('num=',num)
res = []
for i in range(0,len(num),c):
res.append(num[i:i+c])
return res
if __name__ == '__main__':
array = [[np.random.randint(1,10) for j in range(4)] for i in range(4)]
print('num = ',array)
print('row = ')
r = int(input())
print('column = ')
c = int(input())
w = Solution()
res = w.matrixReshape(array, r, c)
print('result:',res)