在机器学习中,我们经常需要对矩阵进行重塑(reshape)操作。给定一个矩阵,将其重塑为一个新的矩阵,但保持其原始数据。
如果重塑前后的元素总数不相同,返回-1
重塑操作应当满足:
1. 新矩阵的元素总数必须与原矩阵相同
2. 原矩阵中的元素在新矩阵中的相对顺序不变
第一行输入要重塑的矩阵。
第二行输入目标矩阵的行数和列数。
输出重塑后的矩阵,返回形式以list形式。
[[1, 2], [3, 4]] (1, 4)
[[1, 2, 3, 4]]
[[1, 2, 3]] (5, 1)
-1
重塑前后元素总数不相等,返回-1
1. Python3对应的输入、输出已给出,您只用实现核心功能函数即可。
2. 支持numpy、scipy、pandas、scikit-learn库。
from typing import List, Tuple, Union
import numpy as np
def reshape_matrix(a: List[List[Union[int, float]]], new_shape: Tuple[int, int]) -> List[List[Union[int, float]]]:
n, m = new_shape
flatten = []
for t in a:
flatten.extend(t)
if len(flatten) != n * m:
return -1
#print(flatten)
ans = []
for i in range(n):
ans.append(flatten[i*m:(i+1)*m])
return ans
def main():
try:
a = eval(input())
new_shape = eval(input())
result = reshape_matrix(a, new_shape)
print(result)
except Exception as e:
print(f"输入格式错误: {e}")
if __name__ == "__main__":
main()