867. Transpose Matrix

题目地址:https://leetcode.com/problems/transpose-matrix/description/

大意:将矩阵的行列转换。

思路: 1.简单的循环操作 2.python 的zip()方法 3.numpy库

class Solution:
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        return list(map(list, zip(*A)))
    def transpose2(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        rows, cols = len(A), len(A[0])
        res = [[0] * rows for _ in range(cols)]
        for row in range(rows):
            for col in range(cols):
                res[col][row] = A[row][col]
        return res
    def transpose3(self,A):
        return np.array(A).T.tolist()

知识点:

  1. zip()方法的使用: zip([iterable, ...])
    zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip解压:
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b)
[(1, 4), (2, 5), (3, 6)]
 zip(a,c)
[(1, 4), (2, 5), (3, 6)]
 zip(*zipped)
[(1, 2, 3), (4, 5, 6)]
  1. map()方法的使用:
    list = map(func, iter)
    其中, func是函数, iter是可迭代的序列。
    它的功能是:将一个序列中的每一个元素应用传入的函数, 并返回一个包含所有函数调用结果的一个列表.
    特别注意的是,python3中返回的是一个对象,转换成函数得用list()方法

3.numpy 库,.T就是二维矩阵的转置,跟上学学的一样。 把原生list转成numpy的array后,再转回来就行了。



所有题目解题方法和答案代码地址:https://github.com/fredfeng0326/LeetCode

你可能感兴趣的:(867. Transpose Matrix)