566. 重塑矩阵
作者:互联网
思路:
将原nums中的元素都读出来,在往新list中加。
1 class Solution(object): 2 def matrixReshape(self, nums, r, c): 3 """ 4 :type nums: List[List[int]] 5 :type r: int 6 :type c: int 7 :rtype: List[List[int]] 8 """ 9 # nums行数 10 r0 = len(nums) 11 # nums列数 12 c0 = len(nums[0]) 13 # 若reshape操作不合理,返回原list 14 if r0 * c0 != r * c: 15 return nums 16 new = [] 17 for i in range(r0): 18 for j in range(c0): 19 new.append(nums[i][j]) 20 ans = [] 21 flag = 0 22 for k in range(r): 23 temp = [] 24 for h in range(c): 25 temp.append(new[flag]) 26 flag += 1 27 ans.append(temp) 28 return ans 29 30 31 if __name__ == '__main__': 32 solution = Solution() 33 print(solution.matrixReshape([[1, 2], [3, 4]], r=1, c=4))
标签:__,nums,int,List,矩阵,566,range,重塑,ans 来源: https://www.cnblogs.com/panweiwei/p/12799816.html