pythonの2ビット配列の作成、遍歴、要素の追加

8120 ワード

leetcodeの前の2次元配列のテーマを例にします:1つの行列を与えて、その回転行列を出力します
方法1:
class Solution:
    def transpose(self, A: List[List[int]]) -> List[List[int]]:
    	    Row = len(A)#            
        Col = len(A[0])#       
        A_transpose = [[] * Row for i in range(Col)] #     、            
        #    ,Row              ,Col              
        for i in range(Col):
            for j in range(Row):
                #      
                A_transpose[i].append(A[j][i])
                                       
        return A_transpose

方法2:
class Solution:
    def transpose(self, A: List[List[int]]) -> List[List[int]]:
        Row = len(A)
        Col = len(A[0])
        A_transpose = []#       
        for i in range(Col):
            a =[]
            for j in range(Row):
                a.append(A[j][i])#        ,      
                
            A_transpose.append(a)
        
        return A_transpose

方法3:より簡潔な書き方
class Solution:
    def transpose(self, A: List[List[int]]) -> List[List[int]]:
        return [[A[i][j] for i in range(len(A))] for j in range(len(A[0]))]